public static void GetPdfThumbnail(string sourcePdfFilePath, string destinationPngFilePath, int StartPage = 1, int EndPage = 1, GhostscriptPageSizes PageSize = GhostscriptPageSizes.a4) { // Use GhostscriptSharp to convert the pdf to a png GhostscriptWrapper.GenerateOutput(sourcePdfFilePath, destinationPngFilePath, new GhostscriptSettings { Device = GhostscriptDevices.pngalpha, Page = new GhostscriptPages { // Only make a thumbnail of the first page Start = StartPage, End = EndPage, AllPages = false }, Resolution = new Size { // Render at 72x72 dpi Height = 300, Width = 300 }, Size = new GhostscriptPageSize { // The dimensions of the incoming PDF must be // specified. The example PDF is US Letter sized. Native = PageSize } } ); }
private async Task <Stream> GetThumbnailPng(byte[] pdfBytes, int size) { try { var inputFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); var outputFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); await File.WriteAllBytesAsync(inputFile, pdfBytes); GhostscriptWrapper.GenerateThumbnail(inputFile, outputFile); var resultStream = new MemoryStream(); using (var image = Image.Load(outputFile)) { image.Mutate(ctx => ctx.Resize(size, size * image.Height / image.Width)); image.SaveAsJpeg(resultStream); } File.Delete(inputFile); File.Delete(outputFile); resultStream.Seek(0, SeekOrigin.Begin); return(resultStream); } catch (Exception ex) { this.logger.LogWarning(ex.Message); return(Stream.Null); } }
public static void WriteOut(int pJpegWidth = 0, int[] pages = null) { var OutputPath = AppDomain.CurrentDomain.BaseDirectory; var sourceFile = "test.pdf"; var jpegFile = Path.ChangeExtension(sourceFile, "jpg"); var settings = new GhostscriptSettings { Page = { AllPages = false, Start = 1, End = 1 }, Size = { Native = GhostscriptPageSizes.a2 }, Device = GhostscriptDevices.png16m, Resolution = new Size(150, 122) }; if (pages.Length > 1) { // PDF contains multiple pages, make each one into a jpg var iPageNumber = 0; foreach (var page in pages) { //FORMAT: GhostscriptWrapper.GenerateOutput(<pdf file path>, <destination jpg path>, <settings>); GhostscriptWrapper.GenerateOutput(OutputPath + sourceFile, OutputPath + jpegFile.Replace(".jpg", "_" + iPageNumber + ".jpg"), settings); // add page number into jpg string iPageNumber++; settings.Page.Start = settings.Page.End = iPageNumber + 1; } } else { //FORMAT: GhostscriptWrapper.GenerateOutput(<pdf file path>, <destination jpg path>, <settings>); GhostscriptWrapper.GenerateOutput(OutputPath + sourceFile, OutputPath + jpegFile, settings); } }
public void Verify(FileInfo pdf) { if (!pdf.Exists) { throw new InvalidOperationException("File to verify does not exist '{0}'".Fmt(pdf.FullName)); } using (var destination = new DisposableFile()) { GhostscriptWrapper.GenerateOutput( inputPath: pdf.FullName, outputPath: destination.File.FullName, settings: new GhostscriptSettings { Device = GhostscriptDevices.tiff24nc, Resolution = new Size(72, 72), Size = new GhostscriptPageSize { Native = GhostscriptPageSizes.letter } }); //GhostScript embeds a creation timestamp on each page of the tiff. Obviously if its different every time the files won't match up byte for byte. So normalize using (var tiff = Tiff.Open(destination.File.FullName, "a")) { Enumerable.Range(0, tiff.NumberOfDirectories()).ForEach(i => { tiff.SetDirectory((short)i); tiff.SetField(TiffTag.DATETIME, Encoding.UTF8.GetBytes("2010:01:01 12:00:00")); //any constant date will do the trick here. tiff.CheckpointDirectory(); }); } Approvals.Verify(GetTiffApprovalWriter(destination.File), GetNamer(), GetReporter()); } }
/// <summary> /// Generate a thumbnail from frontpage of a PDF document. /// </summary> /// <param name="document"></param> /// <param name="documentfile"></param> /// <param name="url"></param> /// <returns></returns> private string GenerateThumbnail(Document document, HttpPostedFileBase documentfile, string url) { if (document.documentUrl.Contains(".pdf")) { string filtype; string seofilename = MakeSeoFriendlyDocumentName(documentfile, out filtype, out seofilename); string documentNameSeo = RegisterUrls.MakeSeoFriendlyString(document.name); string input = Path.Combine(Server.MapPath(Constants.DataDirectory + Document.DataDirectory), document.register.seoname + "_" + documentNameSeo + "_v" + document.versionNumber + "_" + seofilename + "." + filtype); string output = Path.Combine(Server.MapPath(Constants.DataDirectory + Document.DataDirectory), document.register.seoname + "_thumbnail_" + documentNameSeo + "_v" + document.versionNumber + "_" + seofilename + ".jpg"); GhostscriptWrapper.GenerateOutput(input, output, GsSettings()); ImageResizer.ImageJob newImage = new ImageResizer.ImageJob(output, output, new ImageResizer.Instructions("maxwidth=160;maxheight=300;quality=75")); newImage.Build(); return(url + document.register.seoname + "_thumbnail_" + documentNameSeo + "_v" + document.versionNumber + "_" + seofilename + ".jpg"); } else if (document.documentUrl.Contains(".xsd")) { return("/Content/xsd.svg"); } else { return("/Content/pdf.jpg"); } }
private static int Run(string[] arguments) { RedrawConfig config = ArgumentsProcessor.Process(arguments); if (config == null) { return(1); } FileInfo inputFile = new FileInfo(config.InputPath); if (!inputFile.Exists) { Console.WriteLine("Specified input file does not exist"); return(1); } DirectoryInfo outputDir = new DirectoryInfo(Path.GetDirectoryName(config.OutputPath)); if (!outputDir.Exists) { outputDir.Create(); } GhostscriptWrapper.GeneratePageThumbs(inputFile.FullName, config.OutputPath, config.FirstPage, config.LastPage, config.Width, config.Height); return(0); }
private void ButtonGenerate_Click(object sender, EventArgs e) { try { string inputPath = this.textBoxInputPath.Text; string outputPath = this.textBoxOutputPath.Text; int page = (int)this.numericUpDownPage.Value; int resolution = (int)this.numericUpDownResolution.Value; GhostscriptDevices device = (GhostscriptDevices)this.comboBoxDevice.SelectedItem; GhostscriptPageSizes pageSize = (GhostscriptPageSizes)this.comboBoxPageSize.SelectedItem; GhostscriptSettings ghostscriptSettings = new GhostscriptSettings { Page = new GhostscriptPages { Start = page, End = page }, Device = device, Resolution = new Size(resolution, resolution), Size = new GhostscriptPageSize { Native = pageSize } }; GhostscriptWrapper.GenerateOutput(inputPath, outputPath, ghostscriptSettings); Process.Start(outputPath); } catch (Exception exception) { MessageBox.Show(exception.ToString()); } }
public void GenerateMultiplePageThumbnails() { GhostscriptWrapper.GeneratePageThumbs(TEST_FILE_LOCATION, MULTIPLE_FILE_LOCATION, 1, MULTIPLE_FILE_PAGE_COUNT, 100, 100); for (var i = 1; i <= MULTIPLE_FILE_PAGE_COUNT; i++) { Assert.IsTrue(File.Exists(String.Format("output{0}.jpg", i))); } }
public void pdf2ImageByPage(string pdfFile, int pagenumber) //static void pdf2Image(string pptfile, string prefix) { // Do not forget the %d in the output file name @"Example%d.jpg" GhostscriptWrapper.GeneratePageThumbs(exeBase + @"\" + @"d5000.pdf", exeBase + @"\" + @"Example%d.jpg", 1, 15, 100, 100); // for a single page [you have to know the page number -- no function in ghostscript] // GhostscriptWrapper.GeneratePageThumb(exeBase + @"\" + @"d5000.pdf", exeBase + @"\" + @"Example1.jpg", 1, 100, 100); }
public static void VideoThumbNail() { string inpath = "D:\\"; string inext = ".pdf"; var inp = inpath + "one" + inext; var outp = "D:\\three.jpg"; GhostscriptWrapper.GeneratePageThumb(inp, outp, 6, 110, 90); }
public GhostscriptSession GenerateForTesseract(string inputPath) { CreateEnvironment(); var settings = GhostscriptSettingsFactory.Tesseract(); GhostscriptWrapper.GenerateOutput(inputPath, OutputPattern + settings.GetDeviceExtension(), settings); return(this); }
public string GenerateImage(string pathToFile) { string filename = Path.GetFileNameWithoutExtension(pathToFile); string path = "D:\\BookImages\\" + filename + ".png"; Debug.WriteLine(path); GhostscriptWrapper.GeneratePageThumb(pathToFile, path, 1, 120, 250); return(path); }
private IEnumerable <string> ParsePdfDocumentToImages() { FileHelper.CheckFilePathExisting(_pathToPdf); int pdfPageCount = GetPdfPageCount(); string pdfName = Path.GetFileNameWithoutExtension(_pathToPdf); string imagePathTemplate = new FileInfo(_pathToPdf).DirectoryName + @"\" + pdfName + "_0%d.tiff"; GhostscriptWrapper.GeneratePageThumbs(_pathToPdf, imagePathTemplate, 1, pdfPageCount, 200, 200); return(Directory.GetFiles(new FileInfo(_pathToPdf).DirectoryName, pdfName + "_*")); }
//用來轉換PDF成一張一張的jpeg圖片 public void f_ConvertAllPDF(string pdfPath, string savePath) { GhostscriptSettings ghostscriptSettings = new GhostscriptSettings(); ghostscriptSettings.Device = GhostscriptSharp.Settings.GhostscriptDevices.jpeg; //圖片類型 ghostscriptSettings.Size.Native = GhostscriptSharp.Settings.GhostscriptPageSizes.legal; //legal為原尺寸 //ghostscriptSettings.Size.Manual = new System.Drawing.Size(2552, 3579); //此為設定固定尺寸 ghostscriptSettings.Resolution = new System.Drawing.Size(150, 150); //此為解析度 ghostscriptSettings.Page.AllPages = true; GhostscriptWrapper.GenerateOutput(pdfPath, savePath, ghostscriptSettings); Debug.Log("Complete!"); }
public void GenerateSinglePageOutput() { var settings = new GhostscriptSettings { Page = { AllPages = false, Start = 1, End = 1 }, Size = { Native = GhostscriptPageSizes.a2 }, Device = GhostscriptDevices.png16m, Resolution = new Size(150, 122) }; GhostscriptWrapper.GenerateOutput(OutputPath + TEST_FILE_LOCATION, OutputPath + SINGLE_FILE_LOCATION, settings); Assert.IsTrue(File.Exists(OutputPath + SINGLE_FILE_LOCATION)); }
public static string Generate(string file) { using (ApplicationContext.Current.ProfilingLogger.TraceDuration <ThumbnailGenerator>("Started Creatning Thumbnail", "Completed Creating Thumbnail")) { var fileSystem = FileSystemProviderManager.Current.GetFileSystemProvider <MediaFileSystem>(); var outputUrl = GenerateThumbnailFilename(file); var output = fileSystem.GetFullPath(outputUrl); var temp = Path.ChangeExtension(Path.GetRandomFileName(), "pdf"); var tempFilename = Path.Combine(Path.GetDirectoryName(fileSystem.GetFullPath(fileSystem.GetFullPath(file))), temp); var tempOutputFilename = GenerateThumbnailFilename(tempFilename); try { //var source = fileSystem.GetFullPath(file); fileSystem.CopyFile(file, tempFilename); LogHelper.Info <ThumbnailGenerator>($"Generate {tempFilename} to {tempOutputFilename}"); GhostscriptWrapper.GeneratePageThumb(tempFilename, tempOutputFilename, 1, 100, 100); LogHelper.Info <ThumbnailGenerator>($"Generated {tempFilename} to {tempOutputFilename}"); fileSystem.DeleteFile(tempFilename); fileSystem.CopyFile(tempOutputFilename, output); fileSystem.DeleteFile(tempOutputFilename); return(outputUrl); } catch (Exception ex) { LogHelper.Error <ThumbnailGenerator>("Faled generat pdf thumbnail", ex); return(null); } finally { if (fileSystem.FileExists(tempFilename)) { fileSystem.DeleteFile(tempFilename); } if (fileSystem.FileExists(tempOutputFilename)) { fileSystem.DeleteFile(tempOutputFilename); } } } }
private static void PdfToJpg(string path, string fileName, GhostscriptDevices devise, GhostscriptPageSizes pageFormat, int qualityX, int qualityY) { var settingsForConvert = new GhostscriptSettings { Device = devise }; var pageSize = new GhostscriptPageSize { Native = pageFormat }; settingsForConvert.Size = pageSize; settingsForConvert.Resolution = new System.Drawing.Size(qualityX, qualityY); GhostscriptWrapper.GenerateOutput(path, @"C:\YR\Receipt\" + fileName + "_" + ".jpg", settingsForConvert); // here you could set path and name for out put file. }
private void SavePdfToImage(string folder, string filepath) { Logger logger = LogManager.GetCurrentClassLogger(); logger.Info(folder); PdfReader pdfReader = new PdfReader(filepath); int numberOfPages = pdfReader.NumberOfPages; var finalPath = string.Join("/", folder, MULTIPLE_FILE_LOCATION); logger.Info(finalPath); GhostscriptWrapper.GeneratePageThumbs(filepath, finalPath, 1, numberOfPages, 100, 100); }
public GhostscriptSession GenerateOutput(IPdfContent pdfInfo) { CreateEnvironment(); var inputFilename = Id + ".pdf"; var inputPath = Path.Combine(Folder, inputFilename); pdfInfo.WriteAllBytes(inputPath); var settings = GhostscriptSettingsFactory.Default(); GhostscriptWrapper.GenerateOutput(inputPath, OutputPattern + settings.GetDeviceExtension(), settings); return(this); }
public void ConvertToTif() { var destination = new FileInfo(Path.GetTempPath() + "test_ConvertToTif.tif"); GhostscriptWrapper.GenerateOutput( inputPath: TEST_FILE_LOCATION, outputPath: destination.FullName, settings: new GhostscriptSettings { Device = GhostscriptDevices.tiffg4, Resolution = new Size(400, 400), Page = GhostscriptPages.All, Size = new GhostscriptPageSize { Native = GhostscriptPageSizes.a4 }, }); Approvals.VerifyFile(destination.FullName); }
protected override void CreateImage() { GhostscriptUtil.EnsureDll(); string outputFileName = Path.GetTempFileName(); try { string filename = FileSourceHelper.ResolveFileName(SourceFileName); GhostscriptWrapper.GeneratePageThumb(filename, outputFileName, PageNumber, 96, 96); Bitmap = new FastBitmap(File.ReadAllBytes(outputFileName)); } finally { File.Delete(outputFileName); } }
/// <summary> /// Create thumbnail of pdf file /// </summary> /// <param name="mediaFile">pdf file object</param> public string GenerateThumb(MediaFileItem mediaFile) { using (new Tracer()) { try { if (!string.IsNullOrEmpty(mediaFile.ThumbLocation)) { GhostscriptWrapper.GeneratePageThumb(mediaFile.MediaLocation, mediaFile.ThumbLocation, 1, mediaFile.Width, mediaFile.Height); } } catch (Exception ex) { Log.Error(ex); } return(mediaFile.ThumbLocation); } }
//Pdfから画像を取得する private string getImageFromPdf(string baseFilePass, string pdfFielName) { //拡張子無しでファイル名を取得する string imgFileName = Path.GetFileNameWithoutExtension(pdfFielName) + ".png"; try { //Pdfから画像を取得 GhostscriptSettings settings = new GhostscriptSettings(); settings.Page.AllPages = true; //全ページ出力 settings.Page.Start = 1; //出力開始ページ settings.Page.End = 1; //出力終了ページ settings.Size.Native = GhostscriptSharp.Settings.GhostscriptPageSizes.a0; //出力サイズ指定 settings.Device = GhostscriptSharp.Settings.GhostscriptDevices.png256; //出力ファイルフォーマット指定(pngで指定) settings.Resolution = new Size(600, 600); //出力Dpi string inputPath = baseFilePass + "\\" + pdfFielName; string outputPath = baseFilePass + "\\" + imgFileName; GhostscriptWrapper.GenerateOutput(inputPath, outputPath, settings); // Create the initial thumbnail //ファイルが生成されない場合はパスを返さない if (!System.IO.File.Exists(outputPath)) { imgFileName = ""; outLogMsg(pdfFielName, "Pdf埋め込み画像なし"); } else { outLogMsg(pdfFielName, "Pdf画像変換完了"); } } catch (Exception exp) { imgFileName = ""; outLogMsg(pdfFielName, "Pdf画像取得実施エラー : " + exp.Message); } return(imgFileName); }
// Rotina para gerar Thumbnail string gerarThumb(string filename) { string inputPdf = filename; string outputPng = thumbDir + Path.GetFileNameWithoutExtension(filename) + ".png"; string outputPngBig = thumbDir + Path.GetFileNameWithoutExtension(filename) + "_big.png"; //Criar diretório de thumbnails, caso não exista if (!Directory.Exists(thumbDir)) { Directory.CreateDirectory(thumbDir); } if (File.Exists(outputPng) && File.Exists(outputPngBig)) { return(outputPng); } else { if (!File.Exists(outputPng)) { try { GhostscriptWrapper.GeneratePageThumbs(inputPdf, outputPng, 1, 1, 10, 10); } catch { userInfoMsg("!Error: Could not generate thumbnail for the file: " + Path.GetFileName(filename)); } } if (!File.Exists(outputPngBig)) { try { GhostscriptWrapper.GeneratePageThumbs(inputPdf, outputPngBig, 1, 1, 100, 100); } catch { userInfoMsg("!Error: Could not generate preview of the file: " + Path.GetFileName(filename)); } } if (File.Exists(outputPng)) { return(outputPng); } else { return(string.Empty); } } }
/* private int Decoder(string SourcePdfFileName,string DestPdfFileName, string Contact) * { * try * { * * PdfReader pdfReader = new PdfReader(SourcePdfFileName); * * FileStream signedPdfs = new FileStream(DestPdfFileName, FileMode.Create);//the output pdf file * PdfStamper pdfStamper = new PdfStamper(pdfReader, signedPdfs, '\0'); * PdfContentByte pdfData = pdfStamper.GetOverContent(1); * //Create the QR Code/2D Code------------------------------- * Image qrImage = GenerateQRCode(Contact); * iTextSharp.text.Image itsQrCodeImage = iTextSharp.text.Image.GetInstance(qrImage, System.Drawing.Imaging.ImageFormat.Jpeg); * itsQrCodeImage.SetAbsolutePosition(270, 50); * pdfData.AddImage(itsQrCodeImage); * pdfStamper.Close(); * return 1; * } * catch(Exception e) * { * ViewBag.exception = e.Message; * return 0; * } * }*/ private int convertToImage(string sourcePdfFilePath, string destinationPngFilePath) { try { // Use GhostscriptSharp to convert the pdf to a png GhostscriptWrapper.GenerateOutput(sourcePdfFilePath, destinationPngFilePath, new GhostscriptSettings { Device = GhostscriptDevices.pngalpha, Page = new GhostscriptPages { // Only make a thumbnail of the first page Start = 1, End = 1, AllPages = false }, Resolution = new Size { // Render at 72x72 dpi Height = 72, Width = 72 }, Size = new GhostscriptPageSize { // The dimentions of the incoming PDF must be // specified. The example PDF is US Letter sized. Native = GhostscriptPageSizes.a4 } } ); return(1); } catch (Exception e) { ViewBag.exception = e.Message; return(0); } }
public void GenerateSinglePageThumbnail() { GhostscriptWrapper.GeneratePageThumb(TEST_FILE_LOCATION, SINGLE_FILE_LOCATION, 1, 100, 100); Assert.IsTrue(File.Exists(SINGLE_FILE_LOCATION)); }
/// <summary> /// Save document in the server /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnSave_Click(object sender, EventArgs e) { try { string pathServerTemp = Server.MapPath("Portals/0/Images/Temp/"); string pathServerThumbImages = Server.MapPath("Portals/0/ModIma/ThumbImages/"); if (IsChallengeFiles) { if (string.IsNullOrEmpty(ValidateSecurity.ValidateString(txtTitle.Text, false))) { rgvtxtTitle.IsValid = false; return; } //Information of the document challengeFileComponent = new ChallengeFileComponent(Guid.NewGuid()); challengeFileComponent.ChallengeFile.Created = DateTime.Now; challengeFileComponent.ChallengeFile.Updated = challengeFileComponent.ChallengeFile.Created; challengeFileComponent.ChallengeFile.ObjectName = txtFileName.Text; challengeFileComponent.ChallengeFile.ObjectType = ddCategory.SelectedItem.Text; challengeFileComponent.ChallengeFile.Size = FileSize; challengeFileComponent.ChallengeFile.ObjectExtension = ExtensionName; challengeFileComponent.ChallengeFile.Language = Language; challengeFileComponent.ChallengeFile.ChallengeReferenceId = ChallengeReference; try { string pathServer = Server.MapPath(ddCategory.SelectedValue); string sourceFile = System.IO.Path.Combine(pathServerTemp, FileName + ExtensionName); string destFile = System.IO.Path.Combine(pathServer, ValidateSecurity.ValidateString(txtFileName.Text, false) + ValidateSecurity.ValidateString(lblExtension.Text, false)); if (!Directory.Exists(pathServer)) { Directory.CreateDirectory(pathServer); } if (System.IO.File.Exists(sourceFile)) { if (!System.IO.File.Exists(destFile)) { System.IO.File.Move(sourceFile, destFile); } else { System.IO.File.Delete(destFile); System.IO.File.Move(sourceFile, destFile); } } //Save document information in the database challengeFileComponent.ChallengeFile.ObjectLocation = ddCategory.SelectedValue + ValidateSecurity.ValidateString(txtFileName.Text, false) + ValidateSecurity.ValidateString(lblExtension.Text, false); challengeFileComponent.Save(); } catch { } } else { documentComponent = new DocumentComponent(Guid.NewGuid()); UserPropertyComponent user = new UserPropertyComponent(UserId); documentComponent.Document.Created = DateTime.Now; documentComponent.Document.CreatedBy = UserId; documentComponent.Document.Updated = documentComponent.Document.Created; documentComponent.Document.Views = 0; documentComponent.Document.Version = 1; documentComponent.Document.UploadedBy = user.UserProperty.UserId; documentComponent.Document.Author = string.Empty;// user.UserProperty.FirstName + " " + user.UserProperty.LastName; documentComponent.Document.Name = ValidateSecurity.ValidateString(txtFileName.Text, false); documentComponent.Document.Title = ValidateSecurity.ValidateString(txtTitle.Text, false); documentComponent.Document.FileType = ExtensionName; documentComponent.Document.Deleted = false; documentComponent.Document.Description = ValidateSecurity.ValidateString(txtDescription.Text, false); documentComponent.Document.Size = FileSize; documentComponent.Document.Permission = "0"; documentComponent.Document.Scope = rdbScope.SelectedValue; documentComponent.Document.Status = "published"; documentComponent.Document.Category = ddCategory.SelectedValue; documentComponent.Document.DocumentObject = Bytes; documentComponent.Document.ExternalReference = SolutionId; documentComponent.Document.Folder = Folder; //Save information of the document if (documentComponent.Save() < 0) { throw new Exception(); } if (ExtensionName.ToUpper() == ".PDF") { GhostscriptWrapper.GeneratePageThumb(pathServerTemp + FileName + ExtensionName, pathServerThumbImages + "pdf-" + documentComponent.Document.DocumentId.ToString() + ".jpg", 1, 150, 150, 300, 300); } } FillDataRepeater(); WizardFile.ActiveStepIndex = 0; } catch (Exception exc) { Exceptions. ProcessModuleLoadException( this, exc); } }
static void Main(string[] args) { GhostscriptWrapper.GeneratePageThumbs(@"C:\Users\User\Downloads\English_Medium_Extra_for_WEB-2.pdf", "Example.png", 1, 3, 130, 130); }
public void GenerateSinglePagePng() { GhostscriptWrapper.GenerateSinglePagePng(TEST_FILE_LOCATION, SINGLE_PNG_LOCATION, 10); Assert.IsTrue(File.Exists(SINGLE_PNG_LOCATION)); }
public async Task ProcessFileAsync(long id, CloudBlockBlob blob, IBinder binder, ILogger log, CancellationToken token) { var tempDirectory = Path.Combine(Path.GetTempPath(), id.ToString()); try { Directory.CreateDirectory(tempDirectory); await using var sr = await blob.OpenReadAsync(); var directory = blob.Parent; var textBlob = directory.GetBlockBlobReference("text.txt"); textBlob.Properties.ContentType = "text/plain"; var text2 = await _convertDocumentApi.ConvertDocumentPptxToTxtAsync(sr); var text = text2.TextResult; text = StripUnwantedChars(text); await textBlob.UploadTextAsync(text ?? string.Empty); sr.Seek(0, SeekOrigin.Begin); var bytes = await _convertDocumentApi.ConvertDocumentAutodetectToPdfAsync(sr); var inputFileNamePath = Path.Combine(tempDirectory, "in.pdf"); await File.WriteAllBytesAsync(inputFileNamePath, bytes, token); log.LogInformation($"location of file is {inputFileNamePath}"); var outputPath = Path.Combine(tempDirectory, "output"); Directory.CreateDirectory(outputPath); log.LogInformation($"location of output is {outputPath}"); GhostscriptWrapper.GeneratePageThumbs(inputFileNamePath, Path.Combine(outputPath, "%d.jpg"), 1, 1000, 150, 150); var files = Directory.GetFiles(outputPath); textBlob.Metadata["PageCount"] = files.Length.ToString(); await textBlob.SetMetadataAsync(); var tasks = new List <Task>(); foreach (var file in files) { var fileName = int.Parse(Path.GetFileNameWithoutExtension(file)); var blobToUpload = directory.GetBlockBlobReference($"preview-{--fileName}.jpg"); blob.Properties.ContentType = "image/jpeg"; var t = blobToUpload.UploadFromFileAsync(file); tasks.Add(t); //File.Delete(file); } await Task.WhenAll(tasks); } finally { Directory.Delete(tempDirectory, true); } //var text = text2.TextResult; //if (result.Successful == false) //{ // throw new ArgumentException($"ConvertDocumentAutodetectToPngArrayAsync return false in id {id}"); //} //var imagesResult = result.PngResultPages; //var pageCount = imagesResult.Count; //textBlob.Metadata["PageCount"] = pageCount.ToString(); //await textBlob.SetMetadataAsync(); //var starter = await binder.BindAsync<IDurableOrchestrationClient>(new DurableClientAttribute(), token); //await starter.PurgeInstanceHistoryAsync($"ProcessPowerPoint-{id}"); //await starter.StartNewAsync("ProcessPowerPoint", $"ProcessPowerPoint-{id}", new PowerPointOrchestrationInput //{ // Id = id, // Images = imagesResult //}); //var httpClient = await binder.BindAsync<HttpClient>(new HttpClientFactoryAttribute(), token); //var listOfTasks = imagesResult.Select(async imageResult => //{ // var previewBlob = directory.GetBlockBlobReference($"preview-{imageResult.PageNumber - 1}.jpg"); // previewBlob.Properties.ContentType = "image/jpeg"; // await using var imageStream = await httpClient.GetStreamAsync(imageResult.URL); // using var input = Image.Load<Rgba32>(imageStream); // await using var blobWriteStream = await previewBlob.OpenWriteAsync(); // input.SaveAsJpeg(blobWriteStream); //}); //await Task.WhenAll(listOfTasks); }