/// <summary> /// Example of saving Word docx to PDF and to PNG /// https://www.convertapi.com/docx-to-pdf /// https://www.convertapi.com/docx-to-png /// </summary> static void Main(string[] args) { //Get your secret at https://www.convertapi.com/a var convertApi = new ConvertApi("your api secret"); const string sourceFile = @"..\..\..\TestFiles\test.docx"; var fileParam = new ConvertApiParam("File", File.OpenRead(sourceFile)); var convertToPdf = convertApi.ConvertAsync("docx", "pdf", new[] { fileParam }); var outputFileName = convertToPdf.Result.Files[0]; var fileInfo = outputFileName.AsFileAsync(Path.Combine(Path.GetTempPath(), outputFileName.FileName)).Result; Console.WriteLine("The PDF saved to " + fileInfo); var convertToPng = convertApi.ConvertAsync("docx", "png", new[] { //Reuse the same uploaded file parameter fileParam }); foreach (var processedFile in convertToPng.Result.Files) { fileInfo = processedFile.AsFileAsync(Path.Combine(Path.GetTempPath(), processedFile.FileName)).Result; Console.WriteLine("The PNG saved to " + fileInfo); } Console.ReadLine(); }
/// <summary> /// The example shows how to use alternative converters to convert Word document to PDF. /// Build in MS Word converter https://www.convertapi.com/docx-to-pdf /// Custom MS Word printer converter https://www.convertapi.com/docx-to-pdf/printer /// OpenOffice converter https://www.convertapi.com/docx-to-pdf/openoffice /// </summary> static async Task Main(string[] args) { var convertApi = new ConvertApi("8wTuDWLxgHleYS4E"); var pdf1 = Path.Combine(Path.GetTempPath(), $"test-Office-{Guid.NewGuid()}.pdf"); var doc1 = await convertApi.ConvertAsync("docx", "pdf", new ConvertApiFileParam(@"..\..\..\..\TestFiles\test.docx")); await doc1.Files.First().SaveFileAsync(pdf1); Console.WriteLine($"The file converted using Office {pdf1}"); var pdf2 = Path.Combine(Path.GetTempPath(), $"test-Office-Printer-{Guid.NewGuid()}.pdf"); var doc2 = await convertApi.ConvertAsync("docx", "pdf", new ConvertApiFileParam(@"..\..\..\..\TestFiles\test.docx"), new ConvertApiFileParam("Converter", "Printer")); await doc2.Files.First().SaveFileAsync(pdf2); Console.WriteLine($"The file converted using Office {pdf2}"); var pdf3 = Path.Combine(Path.GetTempPath(), $"test-Office-OpenOffice-{Guid.NewGuid()}.pdf"); var doc3 = await convertApi.ConvertAsync("docx", "pdf", new ConvertApiFileParam(@"..\..\..\..\TestFiles\test.docx"), new ConvertApiFileParam("Converter", "OpenOffice")); await doc3.Files.First().SaveFileAsync(pdf3); Console.WriteLine($"The file converted using Office {pdf3}"); }
/// <summary> /// Short example of conversions workflow, the PDF pages extracted and saved as separated JPGs and then ZIP'ed /// https://www.convertapi.com/doc/chaining /// </summary> static async Task Main(string[] args) { try { //Get your secret at https://www.convertapi.com/a var convertApi = new ConvertApi("your api secret"); Console.WriteLine("Converting PDF to JPG and compressing result files with ZIP"); var fileName = Path.Combine(Path.GetTempPath(), "test.pdf"); var firstTask = await convertApi.ConvertAsync("pdf", "jpg", new ConvertApiFileParam(fileName)); Console.WriteLine($"Conversions done. Cost: {firstTask.ConversionCost}. Total files created: {firstTask.FileCount()}"); var secondsTask = await convertApi.ConvertAsync("jpg", "zip", new ConvertApiFileParam(firstTask)); var saveFiles = await secondsTask.Files.SaveFilesAsync(Path.GetTempPath()); Console.WriteLine($"Conversions done. Cost: {secondsTask.ConversionCost}. Total files created: {secondsTask.FileCount()}"); Console.WriteLine($"File saved to {saveFiles.First().FullName}"); } //Catch exceptions from asynchronous methods catch (ConvertApiException e) { Console.WriteLine("Status Code: " + e.StatusCode); Console.WriteLine("Response: " + e.Response); } Console.ReadLine(); }
static async Task Main(string[] args) { if (args.Length == 3) { var convertApi = new ConvertApi(args[0]); var maxSize = Int64.Parse(args[1]); var result = await convertApi.ConvertAsync("pdf", "compress", new[] { new ConvertApiFileParam(args[2]) }); if (result.Files[0].FileSize > Int64.Parse(args[1])) { var splitRes = await convertApi.ConvertAsync("pdf", "split", new[] { new ConvertApiParam("file", result) }); var size = 0; var fileParams = splitRes.Files.ToList().Where(f => { size += f.FileSize; return(size <= maxSize); }) .Select(f => new ConvertApiFileParam(f)); var mergeRes = await convertApi.ConvertAsync("pdf", "merge", fileParams); result = await convertApi.ConvertAsync("pdf", "compress", new[] { new ConvertApiParam("file", mergeRes) }); } result.SaveFilesAsync(Directory.GetCurrentDirectory()).Wait(); } else { Console.WriteLine("Usage: limitpdfsize.exe <CONVERTAPI_SECRET> <SIZE_LIMIT_BYTES> <PDF_FILE>"); } }
/// <summary> /// Example of extracting first page from PDF and then chaining conversion PDF page to JPG. /// https://www.convertapi.com/pdf-to-extract /// https://www.convertapi.com/pdf-to-jpg /// </summary> static void Main(string[] args) { //Get your secret at https://www.convertapi.com/a var convertApi = new ConvertApi("your api secret"); var pdfFile = @"..\..\..\TestFiles\test.pdf"; var extractFirstPage = convertApi.ConvertAsync("pdf", "extract", new[] { new ConvertApiParam("File", File.OpenRead(pdfFile)), new ConvertApiParam("PageRange", "1") }); var thumbnail = convertApi.ConvertAsync("pdf", "jpg", new[] { new ConvertApiParam("File", extractFirstPage.Result), new ConvertApiParam("ScaleImage", "true"), new ConvertApiParam("ScaleProportions", "true"), new ConvertApiParam("ImageHeight", "300"), new ConvertApiParam("ImageWidth", "300") }); var saveFiles = thumbnail.Result.SaveFiles(Path.GetTempPath()); Console.WriteLine("The thumbnail saved to " + saveFiles.First()); Console.ReadLine(); }
/// <summary> /// Example of extracting first and last pages from PDF and then merging them back to new PDF. /// https://www.convertapi.com/pdf-to-split /// https://www.convertapi.com/pdf-to-merge /// </summary> static async Task Main(string[] args) { try { //Get your secret at https://www.convertapi.com/a var convertApi = new ConvertApi("your api secret"); const string sourceFile = @"..\..\..\TestFiles\test.pdf"; var destinationFileName = Path.Combine(Path.GetTempPath(), $"test-merged-{Guid.NewGuid()}.pdf"); var splitTask = await convertApi.ConvertAsync("pdf", "split", new ConvertApiFileParam(sourceFile)); var mergeTask = await convertApi.ConvertAsync("pdf", "merge", new ConvertApiFileParam(splitTask.Files.First()), new ConvertApiFileParam(splitTask.Files.Last())); var saveFiles = await mergeTask.Files.First().SaveFileAsync(destinationFileName); Console.WriteLine("The PDF saved to " + saveFiles); } //Catch exceptions from asynchronous methods catch (ConvertApiException e) { Console.WriteLine("Status Code: " + e.StatusCode); Console.WriteLine("Response: " + e.Response); } Console.ReadLine(); }
/// <summary> /// Create PDF Thumbnail /// Example of extracting first page from PDF and then converting it to JPG using chaining. /// https://www.convertapi.com/pdf-to-extract /// https://www.convertapi.com/pdf-to-jpg /// </summary> static async Task Main(string[] args) { //Get your secret at https://www.convertapi.com/a var convertApi = new ConvertApi("your api secret"); var pdfFile = @"..\..\..\TestFiles\test.pdf"; var extractFirstPage = await convertApi.ConvertAsync("pdf", "extract", new ConvertApiFileParam(pdfFile), new ConvertApiParam("PageRange", "1") ); var thumbnail = await convertApi.ConvertAsync("pdf", "jpg", new ConvertApiFileParam(extractFirstPage), new ConvertApiParam("ScaleImage", "true"), new ConvertApiParam("ScaleProportions", "true"), new ConvertApiParam("ImageHeight", "300"), new ConvertApiParam("ImageWidth", "300") ); var saveFiles = await thumbnail.SaveFilesAsync(Path.GetTempPath()); Console.WriteLine("The thumbnail saved to " + saveFiles.First()); Console.ReadLine(); }
/// <summary> /// Example of saving the same Word docx to PDF and to PNG without uploading the same Word file two times. /// https://www.convertapi.com/docx-to-pdf /// https://www.convertapi.com/docx-to-png /// </summary> static async Task Main(string[] args) { //Get your secret at https://www.convertapi.com/a var convertApi = new ConvertApi("your api secret"); const string sourceFile = @"..\..\..\TestFiles\test.docx"; var fileParam = new ConvertApiFileParam(sourceFile); var convertToPdf = await convertApi.ConvertAsync("docx", "pdf", fileParam); var outputFileName = convertToPdf.Files[0]; var fileInfo = await outputFileName.SaveFileAsync(Path.Combine(Path.GetTempPath(), outputFileName.FileName)); Console.WriteLine("The PDF saved to " + fileInfo); var convertToPng = await convertApi.ConvertAsync("docx", "png", fileParam); foreach (var processedFile in convertToPng.Files) { fileInfo = await processedFile.SaveFileAsync(Path.Combine(Path.GetTempPath(), processedFile.FileName)); Console.WriteLine("The PNG saved to " + fileInfo); } Console.ReadLine(); }
/// <summary> /// The example converting remotely stored file /// </summary> static async Task Main(string[] args) { try { //Get your secret at https://www.convertapi.com/a var convertApi = new ConvertApi("your api secret"); var sourceFile = new Uri("https://cdn.convertapi.com/test-files/presentation.pptx"); Console.WriteLine($"Converting online PowerPoint file {sourceFile} to PDF..."); var convertToPdf = await convertApi.ConvertAsync("pptx", "pdf", new ConvertApiFileParam(sourceFile)); var outputFileName = convertToPdf.Files[0]; var fileInfo = await outputFileName.SaveFileAsync(Path.Combine(Path.GetTempPath(), outputFileName.FileName)); Console.WriteLine("The PDF saved to " + fileInfo); } //Catch exceptions from asynchronous methods catch (ConvertApiException e) { Console.WriteLine("Status Code: " + e.StatusCode); Console.WriteLine("Response: " + e.Response); } Console.ReadLine(); }
/// <summary> /// Token authentication example /// More information https://www.convertapi.com/doc/auth /// </summary> static async Task Main(string[] args) { try { //Get your token and apikey at https://www.convertapi.com/a/auth var convertApi = new ConvertApi("token", 0); var sourceFile = @"..\..\..\TestFiles\test.docx"; var result = await convertApi.ConvertAsync("docx", "pdf", new ConvertApiFileParam(sourceFile) ); var saveFiles = await result.SaveFilesAsync(Path.GetTempPath()); Console.WriteLine("The pdf saved to " + saveFiles.First()); } //Catch exceptions from asynchronous methods catch (ConvertApiException e) { Console.WriteLine("Status Code: " + e.StatusCode); Console.WriteLine("Response: " + e.Response); } Console.ReadLine(); }
/// <summary> /// Example of converting Web Page URL to PDF file /// https://www.convertapi.com/web-to-pdf /// </summary> static async Task Main(string[] args) { try { //Get your secret at https://www.convertapi.com/a var convertApi = new ConvertApi("your api secret"); Console.WriteLine("Converting web page https://en.wikipedia.org/wiki/Data_conversion to PDF..."); var response = await convertApi.ConvertAsync("web", "pdf", new ConvertApiParam("Url", "https://en.wikipedia.org/wiki/Data_conversion"), new ConvertApiParam("FileName", "web-example")); var fileSaved = await response.Files.SaveFilesAsync(Path.GetTempPath()); Console.WriteLine("The web page PDF saved to " + fileSaved.First()); } //Catch exceptions from asynchronous methods catch (ConvertApiException e) { Console.WriteLine("Status Code: " + e.StatusCode); Console.WriteLine("Response: " + e.Response); } Console.ReadLine(); }
/// <summary> /// The example shows how to watermark PDF with text and put overlay PDF. /// https://www.convertapi.com/pdf-to-watermark /// https://www.convertapi.com/pdf-to-watermark-overlay /// </summary> public static async Task Main(string[] args) { try { Console.WriteLine("The example shows how to watermark PDF with text and put overlay PDF"); var sw = new Stopwatch(); sw.Start(); //Get your secret at https://www.convertapi.com/a var convertApi = new ConvertApi("your api secret"); var destinationFileName = Path.Combine(Path.GetTempPath(), $"watermarked-{Guid.NewGuid()}.pdf"); Console.WriteLine("PDF sent for text watermarking..."); var pdfWatermark = await convertApi.ConvertAsync("pdf", "watermark", new ConvertApiFileParam("File", @"..\..\..\TestFiles\test-text.pdf"), new ConvertApiParam("VerticalAlignment", "bottom"), new ConvertApiParam("Text", "This is ConvertAPI watermark %DATETIME%"), new ConvertApiParam("FontSize", 15)); Console.WriteLine("PDF sent for overlay watermarking..."); var pdfWatermarkOverlay = await convertApi.ConvertAsync("pdf", "watermark-overlay", new ConvertApiFileParam("File", pdfWatermark), new ConvertApiFileParam("OverlayFile", new FileInfo(@"..\..\..\TestFiles\pdf-overlay.pdf")), new ConvertApiParam("Style", "stamp"), new ConvertApiParam("Opacity", 50)); var saveFiles = await pdfWatermarkOverlay.Files.First().SaveFileAsync(destinationFileName); Console.WriteLine("The PDF saved to " + saveFiles); sw.Stop(); Console.WriteLine("Elapsed " + sw.Elapsed); Process.Start(saveFiles.ToString()); } //Catch exceptions from asynchronous methods catch (ConvertApiException e) { Console.WriteLine("Status Code: " + e.StatusCode); Console.WriteLine("Response: " + e.Response); } Console.ReadLine(); }
/// <summary> /// Short example of conversions chaining, the PDF pages extracted and saved as separated JPGs and then ZIP'ed /// https://www.convertapi.com/doc/chaining /// </summary> static void Main(string[] args) { //Get your secret at https://www.convertapi.com/a var convertApi = new ConvertApi("your api secret"); Console.WriteLine("Converting PDF to JPG and compressing result files with ZIP"); var fileName = Path.Combine(Path.GetTempPath(), "test.pdf"); var firstTask = convertApi.ConvertAsync("pdf", "jpg", new[] { new ConvertApiParam("File", File.OpenRead(fileName)) }); Console.WriteLine($"Conversions done. Cost: {firstTask.Result.ConversionCost}. Total files created: {firstTask.Result.FileCount()}"); var secondsTask = convertApi.ConvertAsync("jpg", "zip", new[] { new ConvertApiParam("Files", firstTask.Result) }); var saveFiles = secondsTask.Result.SaveFiles(Path.GetTempPath()); Console.WriteLine($"Conversions done. Cost: {secondsTask.Result.ConversionCost}. Total files created: {secondsTask.Result.FileCount()}"); Console.WriteLine($"File saved to {saveFiles.First().FullName}"); Console.ReadLine(); }
public static async Task <FileInfo> GetConvertedResponseBySource(string filePath, string destinationFilePath) { ConvertApi convertApi = new ConvertApi("<your secret key>"); // get secret from https://www.convertapi.com/a via register ConvertApiResponse result = await convertApi.ConvertAsync("xlsx", "pdf", new[] { new ConvertApiFileParam(filePath), }); // save to file var fileInfo = await result.SaveFileAsync(destinationFilePath); return(fileInfo); }
/// <summary> /// The example shows how to merge Word and Powerpoint documents to one PDF by converting them to PDFs and then merging. /// https://www.convertapi.com/docx-to-pdf /// https://www.convertapi.com/pdf-to-merge /// </summary> static async Task Main(string[] args) { try { Console.WriteLine("The example shows how to merge Word and Powerpoint documents to one PDF by converting them to PDFs and then merging. Please wait..."); var sw = new Stopwatch(); sw.Start(); //Get your secret at https://www.convertapi.com/a var convertApi = new ConvertApi("your api secret"); var destinationFileName = Path.Combine(Path.GetTempPath(), $"test-merged-{Guid.NewGuid()}.pdf"); var convertApiFileParam = new ConvertApiFileParam(@"..\..\..\..\TestFiles\test.docx"); var doc1 = convertApi.ConvertAsync("docx", "pdf", convertApiFileParam); Console.WriteLine("Word sent for conversion..."); var doc2 = convertApi.ConvertAsync("pptx", "pdf", new ConvertApiFileParam(@"..\..\..\..\TestFiles\test.pptx")); Console.WriteLine("PowerPoint sent for conversion..."); var mergeTask = await convertApi.ConvertAsync("pdf", "merge", new ConvertApiFileParam(await doc1), new ConvertApiFileParam(await doc2)); var saveFiles = await mergeTask.Files.First().SaveFileAsync(destinationFileName); Console.WriteLine("The PDF saved to " + saveFiles); sw.Stop(); Console.WriteLine("Elapsed " + sw.Elapsed); } //Catch exceptions from asynchronous methods catch (ConvertApiException e) { Console.WriteLine("Status Code: " + e.StatusCode); Console.WriteLine("Response: " + e.Response); } Console.ReadLine(); }
static void Main(string[] args) { try { var urls = new Dictionary <string, string> { { "http://www.tutorialsteacher.com/core/aspnet-core-introduction", "introduction" }, { "http://www.tutorialsteacher.com/core/aspnet-core-environment-setup", "environment-setup" }, { "http://www.tutorialsteacher.com/core/first-aspnet-core-application", "application" }, { "http://www.tutorialsteacher.com/core/aspnet-core-application-project-structure", "project-structure" }, { "http://www.tutorialsteacher.com/core/aspnet-core-wwwroot", "wwwroot" }, { "http://www.tutorialsteacher.com/core/aspnet-core-program", "program" }, { "http://www.tutorialsteacher.com/core/aspnet-core-startup", "startup" }, { "http://www.tutorialsteacher.com/core/net-core-command-line-interface", "command-line-interface" }, { "http://www.tutorialsteacher.com/core/dependency-injection-in-aspnet-core", "dependency-injection" }, { "http://www.tutorialsteacher.com/core/aspnet-core-middleware", "middleware" }, { "http://www.tutorialsteacher.com/core/aspnet-core-logging", "logging" }, { "http://www.tutorialsteacher.com/core/aspnet-core-environment-variable", "environment-variable" }, { "http://www.tutorialsteacher.com/core/aspnet-core-exception-handling", "exception-handling" }, { "http://www.tutorialsteacher.com/core/aspnet-core-static-file", "static-file" }, { "http://www.tutorialsteacher.com/core/dotnet-core-application-types", "application-types" }, { "http://www.tutorialsteacher.com/core/code-sharing-between-dotnet-frameworks", "code-sharing-between-dotnet-frameworks" }, { "http://www.tutorialsteacher.com/core/target-multiple-frameworks-in-aspnet-core2", "target-multiple-frameworks-in-aspnet-core2" }, }; ConvertApi convertApi = new ConvertApi("u3wcYNsxd7x8IeXF"); //foreach (var url in urls) //{ // Console.WriteLine($" url : {url.Key} filename : {url.Value} "); //} foreach (var url in urls) { var saveFiles = convertApi.ConvertAsync("web", "pdf", new ConvertApiParam("Url", url.Key), new ConvertApiParam("FileName", url.Value)) .Result.SaveFiles(@"C:\Users\Akash Karve\Desktop\NETCORE"); } } catch (Exception e) { Console.WriteLine($"{e.GetType()}: {e.Message}"); Console.WriteLine(e.InnerException?.Message); var httpStatusCode = (e.InnerException as ConvertApiException)?.StatusCode; Console.WriteLine("Status Code: " + httpStatusCode); Console.WriteLine("Response: " + (e.InnerException as ConvertApiException)?.Response); } Console.ReadLine(); }
/// <summary> /// The example converting remotely stored file /// </summary> static async Task Main(string[] args) { //Get your secret at https://www.convertapi.com/a var convertApi = new ConvertApi("your api secret"); var sourceFile = new Uri("https://cdn.convertapi.com/cara/testfiles/presentation.pptx"); Console.WriteLine($"Converting online PowerPoint file {sourceFile} to PDF..."); var convertToPdf = await convertApi.ConvertAsync("pptx", "pdf", new ConvertApiFileParam(sourceFile)); var outputFileName = convertToPdf.Files[0]; var fileInfo = await outputFileName.SaveFileAsync(Path.Combine(Path.GetTempPath(), outputFileName.FileName)); Console.WriteLine("The PDF saved to " + fileInfo); Console.ReadLine(); }
/// <summary> /// Example of converting HTML document from stream and getting back PDF stream /// https://www.convertapi.com/docx-to-pdf /// </summary> static async Task Main(string[] args) { //Get your secret at https://www.convertapi.com/a var convertApi = new ConvertApi("your api secret"); const string htmlString = "<!DOCTYPE html><html><body><h1>My First Heading</h1><p>My first paragraph.</p></body></html>"; var stream = new MemoryStream(Encoding.UTF8.GetBytes(htmlString)); var convertToPdf = await convertApi.ConvertAsync("html", "pdf", new ConvertApiFileParam(stream, "test.html") ); var outputStream = await convertToPdf.Files.First().FileStreamAsync(); Console.Write(new StreamReader(outputStream).ReadToEnd()); Console.WriteLine("End of file stream."); Console.ReadLine(); }
// POST: api/Upload public async Task <IHttpActionResult> Post() { var httpRequest = HttpContext.Current.Request; if (httpRequest.Files.Count > 0) //check if request contains file { //get file from the request foreach (string file_Name in httpRequest.Files.Keys) { var file = httpRequest.Files[file_Name]; if (file == null || file.ContentLength == 0) //check if file is bad { return(Content(HttpStatusCode.BadRequest, new { message = "Length of received file is 0. Either you submitted an empty file, or no file was selected before submission." })); } //file paths to store the uploaded and converted files in var file_Path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "document.docx"); var converted_file_Path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "document.pdf"); file.SaveAs(file_Path); try { //ConvertAPI client code to convert docx to pdf ConvertApiResponse result = await convertApi.ConvertAsync("docx", "pdf", new[] { new ConvertApiFileParam(File.OpenRead(file_Path), "document.docx") }); File.Delete(converted_file_Path); // save to file var fileInfo = await result.SaveFileAsync(converted_file_Path); return(Ok()); } catch (Exception e) { return(Content(HttpStatusCode.BadRequest, new { message = "An error occurred while attempting to convert the file to PDF. The error is: " + e.Message })); } } } return(Content(HttpStatusCode.BadRequest, new { message = "No file was found in the request." })); }
/// <summary> /// The example shows how to handle a ConvertAPI exception and write details about it /// </summary> public static async Task Main(string[] args) { try { var convertApi = new ConvertApi("your api secret"); const string sourceFile = @"..\..\..\TestFiles\test.docx"; var convert = await convertApi.ConvertAsync("pdf", "split", new ConvertApiFileParam(sourceFile)); } //Catch exceptions and write details catch (ConvertApiException e) { Console.WriteLine("Status Code: " + e.StatusCode); Console.WriteLine("Response: " + e.Response); } Console.ReadLine(); }
static void Main(string[] args) { //Get your secret at https://www.convertapi.com/a var convertApi = new ConvertApi("your api secret"); const string sourceFile = "https://cdn.convertapi.com/cara/testfiles/presentation.pptx"; var fileParam = new ConvertApiParam("File", sourceFile); var convertToPdf = convertApi.ConvertAsync("pptx", "pdf", new[] { fileParam }); var outputFileName = convertToPdf.Result.Files[0]; var fileInfo = outputFileName.AsFileAsync(Path.Combine(Path.GetTempPath(), outputFileName.FileName)).Result; Console.WriteLine("The PDF saved to " + fileInfo); }
/// <summary> /// Example of converting Web Page URL to PDF file /// https://www.convertapi.com/web-to-pdf /// </summary> static void Main(string[] args) { try { //Get your secret at https://www.convertapi.com/a var convertApi = new ConvertApi("your api secret", 180); var saveFiles = convertApi.ConvertAsync("web", "pdf", new[] { new ConvertApiParam("Url", "https://en.wikipedia.org/wiki/Data_conversion"), new ConvertApiParam("FileName", "web-example") }).Result.SaveFiles(Path.GetTempPath()); Console.WriteLine("The web page PDF saved to " + saveFiles.First()); } //Catch exceptions from asynchronous methods catch (AggregateException e) { Console.WriteLine($"{e.GetType()}: {e.Message}"); Console.WriteLine(e.InnerException?.Message); var httpStatusCode = (e.InnerException as ConvertApiException)?.StatusCode; Console.WriteLine("Status Code: " + httpStatusCode); Console.WriteLine("Response: " + (e.InnerException as ConvertApiException)?.Response); } Console.ReadLine(); }
public IActionResult CreateNote( [FromForm] IFormFile file, [FromForm] string name, [FromForm] string description, [FromForm] decimal price, [FromForm] int semester, [FromForm] int course ) { if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(description) || price <= 0.0m) { return(BadRequest("Input form data error")); } if (file.Length <= 0) { return(BadRequest("File error")); } var ext = file.FileName.Split('.', StringSplitOptions.RemoveEmptyEntries).Last(); var extension = Enum.Parse(typeof(Extension), ext, true) as Extension?; if (extension == null) { throw new UnsupportedMediaTypeException("unsupported", null); } var fileSize = file.Length; if (fileSize > maxFileSize) { return(BadRequest("Maximum file size (10Mb) exceeded")); } var userId = _user.GetCurrentUserId(); var user = _userService.GetById(userId); if (user == null) { return(BadRequest("Invalid user")); } var path = Path.Combine( Directory.GetParent(Directory.GetCurrentDirectory()).FullName, "uploads", userId.ToString()); Directory.CreateDirectory(path); var noteId = Guid.NewGuid(); var note = new Note { Id = noteId, Author = user, AuthorId = user.Id, Name = name, Price = price, Description = description, CourseId = course, FileExtension = extension.Value, Semester = semester }; var notepath = Path.Combine(path, noteId.ToString()); using (var fileStream = new FileStream(notepath, FileMode.Create)) { file.CopyTo(fileStream); fileStream.Seek(0, SeekOrigin.Begin); if (!new[] { Extension.ZIP, Extension.RAR }.Contains(extension.Value)) { var convertApi = new ConvertApi(_configuration["ConvertApi:Secret"]); var thumbnail = convertApi.ConvertAsync(extension.ToString(), "jpg", new ConvertApiFileParam(fileStream, $"{noteId.ToString()}.{extension.ToString()}"), new ConvertApiParam("ScaleImage", "true"), new ConvertApiParam("ScaleProportions", "true"), new ConvertApiParam("ImageHeight", "250"), new ConvertApiParam("ImageWidth", "250"), new ConvertApiParam("ScaleIfLarger", "true"), new ConvertApiParam("JpgQuality", 10)); var previews = thumbnail.Result.FilesStream().ToList(); note.PageCount = previews.Count; var container = GetCloudBlobContainer(); var blockBlob = container.GetBlockBlobReference($"previews/{noteId.ToString()}"); blockBlob.UploadFromStreamAsync(previews.First()); note.PreviewUrl = blockBlob.SnapshotQualifiedStorageUri.PrimaryUri.ToString(); var i = 1; foreach (var preview in previews.Skip(1)) { blockBlob = container.GetBlockBlobReference($"previews/{noteId.ToString()}-{i}"); blockBlob.UploadFromStreamAsync(preview); i += 1; } } } _noteService.Create(note); return(Ok(new { note.Id })); }
private static Task Convert(List <ConvertApiFileParam> fileParams, ConvConfig cfg, List <BlockingCollection <ConvertApiFileParam> > outQueues) { var fileNamesStr = string.Join(", ", fileParams.Select(f => f.GetValueAsync().Result.FileName).ToList()); // Console.WriteLine($"Converting: {fileNamesStr} -> {cfg.DestinationFormat}"); var orderedFileParams = fileParams.OrderBy(fp => fp.GetValueAsync().Result.FileName).ToList(); var srcFormat = orderedFileParams.First().GetValueAsync().Result.FileExt; var convertParams = orderedFileParams.Cast <ConvertApiBaseParam>().Concat(cfg.Params).ToList(); Cde?.AddCount(); _concSem.Wait(); return(_convertApi.ConvertAsync(srcFormat, cfg.DestinationFormat, convertParams) .ContinueWith(tr => { _concSem.Release(); if (tr.IsCompletedSuccessfully) { try { tr.Result.Files.ToList().ForEach(resFile => { if (outQueues.Any()) { var fp = new ConvertApiFileParam(resFile.Url); outQueues.ForEach(action: q => q.Add(fp)); Cde?.Signal(); } if (!outQueues.Any() || cfg.SaveIntermediate) { resFile.SaveFileAsync(Path.Join(cfg.Directory.FullName, resFile.FileName)) .ContinueWith(tfi => { Console.WriteLine(tfi.Result.FullName); Cde?.Signal(); if (Cde?.CurrentCount == 1) { Cde?.Signal(); // Removing initial count to unblock wait } }); } }); } catch (ConvertApiException e) { Console.Error.WriteLine($"Unable to convert: {fileNamesStr} -> {cfg.DestinationFormat}\n{e.Message}\n{e.Response}"); } catch (Exception e) { Console.Error.WriteLine($"Unable to convert: {fileNamesStr} -> {cfg.DestinationFormat}\n{e.Message}"); } } else { Console.Error.WriteLine($"Unable to convert: {fileNamesStr} -> {cfg.DestinationFormat}\n{tr.Exception?.Flatten().Message}"); Cde?.Signal(); if (Cde?.CurrentCount == 1) { Cde?.Signal(); // Removing initial count to unblock wait } } })); }