public static void Run() { // ExStart:DetermineCorrectPassword // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures(); // Load source PDF file PdfFileInfo info = new PdfFileInfo(); info.BindPdf(dataDir + "IsPasswordProtected.pdf"); // Determine if the source PDF is encrypted Console.WriteLine("File is password protected " + info.IsEncrypted); String[] passwords = new String[5] { "test", "test1", "test2", "test3", "sample" }; for (int passwordcount = 0; passwordcount < passwords.Length; passwordcount++) { try { Document doc = new Document(dataDir + "IsPasswordProtected.pdf", passwords[passwordcount]); if (doc.Pages.Count > 0) { Console.WriteLine("Number of Page in document are = " + doc.Pages.Count); } } catch (InvalidPasswordException) { Console.WriteLine("Password = "******" is not correct"); } } // ExEnd:DetermineCorrectPassword }
public static bool isFileProtected(MemoryStream file) { ApplyLicense(); PdfFileInfo info = new PdfFileInfo(file); return(info.IsEncrypted || info.HasOpenPassword || info.HasEditPassword); }
public static void Run() { // ExStart:DetermineCorrectPassword // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures(); // Load source PDF file PdfFileInfo info = new PdfFileInfo(); info.BindPdf(dataDir + "IsPasswordProtected.pdf"); // Determine if the source PDF is encrypted Console.WriteLine("File is password protected " + info.IsEncrypted); String[] passwords = new String[5] { "test", "test1", "test2", "test3", "sample" }; for (int passwordcount = 0; passwordcount < passwords.Length; passwordcount++) { try { Document doc = new Document(dataDir + "IsPasswordProtected.pdf", passwords[passwordcount]); if (doc.Pages.Count > 0) Console.WriteLine("Number of Page in document are = " + doc.Pages.Count); } catch (InvalidPasswordException) { Console.WriteLine("Password = "******" is not correct"); } } // ExEnd:DetermineCorrectPassword }
private void ParsePDF(ref FileObject fo, string filePath) { Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(filePath); PdfFileInfo pi = new PdfFileInfo(pdfDocument); PdfExtractor pe = new PdfExtractor(pdfDocument); ImagePlacementAbsorber abs = new ImagePlacementAbsorber(); fo.pageCount = pi.NumberOfPages; fo.embeddedDocsCount = pdfDocument.EmbeddedFiles.Count; pdfDocument.Pages.Accept(abs); fo.imageCount = abs.ImagePlacements.Count; fo.hasPassword = pi.HasOpenPassword; pe.ExtractText(Encoding.ASCII); string tmpFolderToExtract = tmpFolder + "\\" + Guid.NewGuid(); Directory.CreateDirectory(tmpFolderToExtract); string tmpTextFile = tmpFolderToExtract + "\\" + "tmpTextexport.txt"; pe.GetText(tmpTextFile); fo.wordCount = GetWordCount(tmpTextFile); fo.characterCount = GetCharCount(tmpTextFile); if (File.Exists(tmpTextFile)) { File.Delete(tmpTextFile); } if (Directory.Exists(tmpFolderToExtract)) { Directory.Delete(tmpFolderToExtract); } }
public static void Run() { // ExStart:AddPageNumber // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdfFacades_StampsWatermarks(); // Create PdfFileStamp object PdfFileStamp fileStamp = new PdfFileStamp(); // Open Document fileStamp.BindPdf(dataDir + "AddPageNumber.pdf"); // Get total number of pages int totalPages = new PdfFileInfo(dataDir + "AddPageNumber.pdf").NumberOfPages; // Create formatted text for page number FormattedText formattedText = new FormattedText("Page # Of " + totalPages, System.Drawing.Color.Blue, System.Drawing.Color.Gray, Aspose.Pdf.Facades.FontStyle.Courier, EncodingType.Winansi, false, 14); // Set starting number for first page; you might want to start from 2 or more fileStamp.StartingNumber = 1; // Add page number fileStamp.AddPageNumber(formattedText, 0); // Save updated PDF file fileStamp.Save(dataDir + "AddPageNumber_out.pdf"); // Close fileStamp fileStamp.Close(); // ExEnd:AddPageNumber }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdfFacades_StampsWatermarks(); //create PdfFileStamp object PdfFileStamp fileStamp = new PdfFileStamp(); //Open Document fileStamp.BindPdf(dataDir + "Input_new.pdf"); //get total number of pages int totalPages = new PdfFileInfo(dataDir + "Input_new.pdf").NumberOfPages; //create formatted text for page number FormattedText formattedText = new FormattedText("Page # Of " + totalPages, System.Drawing.Color.Blue, System.Drawing.Color.Gray, Aspose.Pdf.Facades.FontStyle.Courier, EncodingType.Winansi, false, 14); //set starting number for first page; you might want to start from 2 or more fileStamp.StartingNumber = 1; //add page number fileStamp.AddPageNumber(formattedText, 0); //save updated PDF file fileStamp.Save(dataDir + "AddPageNumber_out.pdf"); //close fileStamp fileStamp.Close(); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); // load the source PDF doucment PdfFileInfo fileInfo = new PdfFileInfo(dataDir + @"input.pdf"); // determine that source PDF file is Encrypted with password bool encrypted = fileInfo.IsEncrypted; // MessageBox displays the current status related to PDf encryption Console.WriteLine(encrypted.ToString()); }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures(); // load the source PDF doucment PdfFileInfo fileInfo = new PdfFileInfo(dataDir + @"IsPasswordProtected.pdf"); // determine that source PDF file is Encrypted with password bool encrypted = fileInfo.IsEncrypted; // MessageBox displays the current status related to PDf encryption Console.WriteLine(encrypted.ToString()); }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures(); // load the source PDF doucment PdfFileInfo fileInfo = new PdfFileInfo(dataDir+ @"IsPasswordProtected.pdf"); // determine that source PDF file is Encrypted with password bool encrypted = fileInfo.IsEncrypted; // MessageBox displays the current status related to PDf encryption Console.WriteLine(encrypted.ToString()); }
public static void Run() { // ExStart:RotatingStamp // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdfFacades_TechnicalArticles(); // Set path of the image to be set as watermark string imageFile = dataDir + "aspose-logo.jpg"; // Set input file path string inFile = dataDir + "inFile.pdf"; // Set output file path string outFile = dataDir + "RotatingStamp_out.pdf"; // Create PdfFileInfo object to get height and width of the pages PdfFileInfo fileInfo = new PdfFileInfo(inFile); // Create Stamp object Aspose.Pdf.Facades.Stamp aStamp = new Aspose.Pdf.Facades.Stamp(); // Bind image file with the Stamp object aStamp.BindImage(imageFile); // Specify whether the stamp will be added as a background or not aStamp.IsBackground = false; // Specifies at which pages to add the watermark aStamp.Pages = new int[] { 1 }; // Specifies the watermark rotation - rotate at 90 degrees the stamp is rotated about the center point of the stamp object aStamp.Rotation = 90; // Specifies the position of stamp - lower left corner of the stamp aStamp.SetOrigin(fileInfo.GetPageWidth(1) / 2, fileInfo.GetPageHeight(1) / 2); // Set the size of the watermark aStamp.SetImageSize(100, 100); Document doc = new Document(inFile); // Create PdfFileStamp class to bind input and output files PdfFileStamp stamper = new PdfFileStamp(doc); // Add the stamp in the PDF file stamper.AddStamp(aStamp); // Close the PdfFileStamp object stamper.Close(); // ExEnd:RotatingStamp }
public static void Main() { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //open document PdfFileInfo fileInfo = new PdfFileInfo(dataDir+ "input.pdf"); //set PDF information fileInfo.Author = "Aspose"; fileInfo.Title = "Hello World!"; fileInfo.Keywords = "Peace and Development"; fileInfo.Creator = "Aspose"; fileInfo.CreationDate = DateTime.Now.ToString(); fileInfo.ModDate = DateTime.Now.ToString(); //save updated file fileInfo.SaveNewInfo(dataDir+ "output.pdf"); }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdfFacades_WorkingDocuments(); //open document PdfFileInfo fileInfo = new PdfFileInfo(dataDir + "SetFileInfo.pdf"); //set PDF information fileInfo.Author = "Aspose"; fileInfo.Title = "Hello World!"; fileInfo.Keywords = "Peace and Development"; fileInfo.Creator = "Aspose"; fileInfo.CreationDate = DateTime.Now.ToString(); fileInfo.ModDate = DateTime.Now.ToString(); //save updated file fileInfo.SaveNewInfo(dataDir + "SetFileInfo_out.pdf"); }
public static void Main() { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //open document PdfFileInfo fileInfo = new PdfFileInfo(dataDir+ "input.pdf"); //get PDF information Console.WriteLine("Subject: {0}", fileInfo.Subject); Console.WriteLine("Title: {0}", fileInfo.Title); Console.WriteLine("Keywords: {0}", fileInfo.Keywords); Console.WriteLine("Creator: {0}", fileInfo.Creator); Console.WriteLine("Creation Date: {0}", fileInfo.CreationDate); Console.WriteLine("Modification Date: {0}", fileInfo.ModDate); //find whether is it valid PDF and it is encrypted as well Console.WriteLine("Is Valid PDF: {0}", fileInfo.IsPdfFile); Console.WriteLine("Is Encrypted: {0}", fileInfo.IsEncrypted); }
public static void Run() { // ExStart:SetFileInfo // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdfFacades_WorkingDocuments(); // Open document PdfFileInfo fileInfo = new PdfFileInfo(dataDir+ "SetFileInfo.pdf"); // Set PDF information fileInfo.Author = "Aspose"; fileInfo.Title = "Hello World!"; fileInfo.Keywords = "Peace and Development"; fileInfo.Creator = "Aspose"; // Save updated file fileInfo.SaveNewInfo(dataDir+ "SetFileInfo_out.pdf"); // ExEnd:SetFileInfo }
public static void Run() { // ExStart:SetFileInfo // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdfFacades_WorkingDocuments(); // Open document PdfFileInfo fileInfo = new PdfFileInfo(dataDir + "SetFileInfo.pdf"); // Set PDF information fileInfo.Author = "Aspose"; fileInfo.Title = "Hello World!"; fileInfo.Keywords = "Peace and Development"; fileInfo.Creator = "Aspose"; // Save updated file fileInfo.SaveNewInfo(dataDir + "SetFileInfo_out_.pdf"); // ExEnd:SetFileInfo }
public static void Main() { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //open document PdfFileInfo fileInfo = new PdfFileInfo(dataDir + "input.pdf"); //set PDF information fileInfo.Author = "Aspose"; fileInfo.Title = "Hello World!"; fileInfo.Keywords = "Peace and Development"; fileInfo.Creator = "Aspose"; fileInfo.CreationDate = DateTime.Now.ToString(); fileInfo.ModDate = DateTime.Now.ToString(); //save updated file fileInfo.SaveNewInfo(dataDir + "output.pdf"); }
/// <summary> /// Adds a bookmark to the first page of each of the given PDFs in the Tuple's byte array, using the string in that Tuple for the /// title of the bookmark. /// </summary> /// <param name="pdf">PDF byte array</param> /// <param name="titleAndPdfs">Tuples of <Bookmark title, PDF byte array></param> /// <returns>PDF byte array</returns> private static byte[] addBookmarksToPdf(byte[] pdf, IEnumerable <Tuple <string, byte[]> > titleAndPdfs) { using (var tmpPdf = new MemoryStream(pdf)) { var bookmarkEditor = new PdfBookmarkEditor(); bookmarkEditor.BindPdf(tmpPdf); var count = 1; foreach (var titleAndPdf in titleAndPdfs) { bookmarkEditor.CreateBookmarkOfPage(titleAndPdf.Item1, count); count += new PdfFileInfo(new MemoryStream(titleAndPdf.Item2)).NumberOfPages; } using (var addBookmarksStream = new MemoryStream()) { bookmarkEditor.Save(addBookmarksStream); return(addBookmarksStream.ToArray()); } } }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdfFacades_WorkingDocuments(); //open document PdfFileInfo fileInfo = new PdfFileInfo(dataDir + "GetFileInfo.pdf"); //get PDF information Console.WriteLine("Subject: {0}", fileInfo.Subject); Console.WriteLine("Title: {0}", fileInfo.Title); Console.WriteLine("Keywords: {0}", fileInfo.Keywords); Console.WriteLine("Creator: {0}", fileInfo.Creator); Console.WriteLine("Creation Date: {0}", fileInfo.CreationDate); Console.WriteLine("Modification Date: {0}", fileInfo.ModDate); //find whether is it valid PDF and it is encrypted as well Console.WriteLine("Is Valid PDF: {0}", fileInfo.IsPdfFile); Console.WriteLine("Is Encrypted: {0}", fileInfo.IsEncrypted); }
public static void Main() { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //open document PdfFileInfo fileInfo = new PdfFileInfo(dataDir + "input.pdf"); //get PDF information Console.WriteLine("Subject: {0}", fileInfo.Subject); Console.WriteLine("Title: {0}", fileInfo.Title); Console.WriteLine("Keywords: {0}", fileInfo.Keywords); Console.WriteLine("Creator: {0}", fileInfo.Creator); Console.WriteLine("Creation Date: {0}", fileInfo.CreationDate); Console.WriteLine("Modification Date: {0}", fileInfo.ModDate); //find whether is it valid PDF and it is encrypted as well Console.WriteLine("Is Valid PDF: {0}", fileInfo.IsPdfFile); Console.WriteLine("Is Encrypted: {0}", fileInfo.IsEncrypted); }
public static PdfFileInfo GetFileInfo(string fullFileName) { PdfReader pdfReader = new PdfReader(fullFileName); List <object[]> fonts = BaseFont.GetDocumentFonts(pdfReader); string creationDate = pdfReader.Info.GetValueOrDefault("CreationDate"); string modificationDate = pdfReader.Info.GetValueOrDefault("ModDate"); var fileInfo = new PdfFileInfo { Creator = pdfReader.Info.GetValueOrDefault("Creator"), Producer = pdfReader.Info.GetValueOrDefault("Producer"), CreationDate = ParseDateTime(creationDate), ModificationDate = ParseDateTime(modificationDate), EmbeddedFonts = CreateEmbeddedFontsList(fonts) }; pdfReader.Close(); return(fileInfo); }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdfFacades_WorkingDocuments(); //open document PdfFileInfo fileInfo = new PdfFileInfo(dataDir+ "GetFileInfo.pdf"); //get PDF information Console.WriteLine("Subject: {0}", fileInfo.Subject); Console.WriteLine("Title: {0}", fileInfo.Title); Console.WriteLine("Keywords: {0}", fileInfo.Keywords); Console.WriteLine("Creator: {0}", fileInfo.Creator); Console.WriteLine("Creation Date: {0}", fileInfo.CreationDate); Console.WriteLine("Modification Date: {0}", fileInfo.ModDate); //find whether is it valid PDF and it is encrypted as well Console.WriteLine("Is Valid PDF: {0}", fileInfo.IsPdfFile); Console.WriteLine("Is Encrypted: {0}", fileInfo.IsEncrypted); }
public static void Main() { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //open document PdfFileStamp fileStamp = new PdfFileStamp(dataDir + "Input_new.pdf", dataDir + "output.pdf"); //get total number of pages int totalPages = new PdfFileInfo(dataDir + "Input_new.pdf").NumberOfPages; //create formatted text for page number FormattedText formattedText = new FormattedText("Page # Of " + totalPages, System.Drawing.Color.Blue, System.Drawing.Color.Gray, Aspose.Pdf.Facades.FontStyle.Courier, EncodingType.Winansi, false, 14); //set starting number for first page; you might want to start from 2 or more fileStamp.StartingNumber = 1; //add page number fileStamp.AddPageNumber(formattedText, 0); //save updated PDF file fileStamp.Close(); }
public static void Main() { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //open document PdfFileStamp fileStamp = new PdfFileStamp(dataDir+ "Input_new.pdf", dataDir+ "output.pdf"); //get total number of pages int totalPages = new PdfFileInfo(dataDir+ "Input_new.pdf").NumberOfPages; //create formatted text for page number FormattedText formattedText = new FormattedText("Page # Of " + totalPages, System.Drawing.Color.Blue, System.Drawing.Color.Gray, Aspose.Pdf.Facades.FontStyle.Courier, EncodingType.Winansi, false, 14); //set starting number for first page; you might want to start from 2 or more fileStamp.StartingNumber = 1; //add page number fileStamp.AddPageNumber(formattedText, 0); //save updated PDF file fileStamp.Close(); }
// todo : This needs a better name public static byte[] DoThis(string pdfPath, string barCodeImagePath) { // todo : This needs to be a byte[] passed into the method var pathToSavePDf = AppDomain.CurrentDomain.BaseDirectory + "Document\\PDFBarCodeAttached.pdf"; // todo : This needs to be a byte[] passed into the method var barcode = File.ReadAllBytes(barCodeImagePath); //todo : This needs to be in a using statement! var stream = new MemoryStream(); stream.Write(barcode, 0, barcode.Length); // todo : This needs to be in a using statment! var mender = new PdfFileMend(pdfPath, pathToSavePDf); var fileInfo = new PdfFileInfo(pdfPath); //todo : this must be in a using method! // todo : These values need to be passed into the DoThis method! var lowerLeftX = 100f; var lowerLeftY = 100f; var upperRightX = 200f; var upperRightY = 200f; var filePages = fileInfo.NumberOfPages; // why would we add it to each page? // todo : Take page number as a paraemter into this method! for (var pageNumber = 1; pageNumber <= filePages; pageNumber++) { mender.AddImage(stream, pageNumber, lowerLeftX, lowerLeftY, upperRightX, upperRightY); } mender.Close(); stream.Close(); return(barcode); }
/// <summary> /// Adds a bookmark to the first page of each of the given PDFs in the Tuple's byte array, using the string in that Tuple for the /// title of the bookmark. /// </summary> /// <param name="pdf">PDF byte array</param> /// <param name="titleAndPdfs">Tuples of <Bookmark title, PDF byte array></param> /// <returns>PDF byte array</returns> private static byte[] addBookmarksToPdf( byte[] pdf, IEnumerable<Tuple<string, byte[]>> titleAndPdfs ) { using( var tmpPdf = new MemoryStream( pdf ) ) { var bookmarkEditor = new PdfBookmarkEditor(); bookmarkEditor.BindPdf( tmpPdf ); var count = 1; foreach( var titleAndPdf in titleAndPdfs ) { bookmarkEditor.CreateBookmarkOfPage( titleAndPdf.Item1, count ); count += new PdfFileInfo( new MemoryStream( titleAndPdf.Item2 ) ).NumberOfPages; } using( var addBookmarksStream = new MemoryStream() ) { bookmarkEditor.Save( addBookmarksStream ); return addBookmarksStream.ToArray(); } } }
public MemoryStream ConvertToPdf(DocumentInfo file) { var fileName = file.FileName; var fileType = _fileTypeDetector.Detect(new MemoryStream(file.Body)); var streamToConvert = new MemoryStream(file.Body) {Position = 0}; var resultStream = new MemoryStream(); switch (fileType) { case EnumFileType.Word: case EnumFileType.Word2007: try { var word2007Doc = new Document(streamToConvert); word2007Doc.Unprotect(); word2007Doc.Save(resultStream, WordSaveFormat.Pdf); } catch (FileNotFoundException e) { _log.ErrorFormat("Errore nella conversione di un file - {0} - fileName:{1}", e, Library.Utility.GetMethodDescription(), fileName); } break; case EnumFileType.Excel: case EnumFileType.Excel2007: var cells = new Workbook(streamToConvert); try { cells.Save(resultStream, CellsSaveFormat.Pdf); } catch (CellsException e) { _log.ErrorFormat("Errore nella conversione di un file - {0} - fileName:{1}", e, Library.Utility.GetMethodDescription(), fileName); } catch (FileNotFoundException e) { _log.ErrorFormat("Errore nella conversione di un file - FILE NON TROVATO - {0} - fileName:{1}", e, Library.Utility.GetMethodDescription(), fileName); } catch (Exception e) { // Here we have the workaround for "Unsupported sfnt version" exception. if (resultStream.Length == 0) cells.Save(resultStream, CellsSaveFormat.Pdf); _log.ErrorFormat("Errore nella conversione di un file - WORKAROUND for 'Unsupported sfnt version' - {0} - fileName:{1}", e, Library.Utility.GetMethodDescription(), fileName); } break; case EnumFileType.PowerPoint: case EnumFileType.PowerPoint2007: try { var slides = new Presentation(streamToConvert, new SlidesLoadOptions { LoadFormat = SlidesLoadFormat.Ppt }); slides.Save(resultStream, SlidesSaveFormat.Pdf); } catch (PptException e) { _log.ErrorFormat("Errore nella conversione di un file - {0} - fileName:{1}", e, Library.Utility.GetMethodDescription(), fileName); } catch (FileNotFoundException e) { _log.ErrorFormat("Errore nella conversione di un file - FILE NON TROVATO - {0} - fileName:{1}", e, Library.Utility.GetMethodDescription(), fileName); } break; case EnumFileType.Pdf: var pdf = new PdfFileInfo(streamToConvert); var numberOfPage = pdf.NumberOfPages; var pdfEditor = new PdfFileEditor(); pdfEditor.Extract(streamToConvert, 1, numberOfPage, resultStream); break; case EnumFileType.Png: imageToPdf(streamToConvert, resultStream, ImageFileType.Png); break; case EnumFileType.Bmp: imageToPdf(streamToConvert, resultStream, ImageFileType.Bmp); break; case EnumFileType.Jpg: imageToPdf(streamToConvert, resultStream, ImageFileType.Jpeg); //streamToConvert.CopyTo(resultStream); break; default: _log.ErrorFormat("Unknown file type, conversion failed - {0} - fileName:{1}", Library.Utility.GetMethodDescription(), fileName); break; } _log.InfoFormat("File converted successfully - {0} - fileName:{1}", Library.Utility.GetMethodDescription(), fileName); resultStream.Position = 0; return resultStream; }
/// <summary> /// Вставляет изображения штампов электронной подписи на первую страницу указанного PDF-файла /// </summary> /// <param name="sessionContext">Контекст сессии</param> /// <param name="generatorType">Тип генератора изображений штампов электронной подписи</param> /// <param name="images">Массив изображений штампов электронной подписи</param> /// <param name="fileStream">Поток, содержащий PDF-файл, в который необходимо вставить указанные изображения</param> /// <returns>Модель файла со вставленными изображениями</returns> public GeneratedFileInfo Generate(SessionContext sessionContext, ImageGeneratorType generatorType, System.Drawing.Image[] images, Stream fileStream) { if (images is null) { throw new ArgumentNullException(nameof(images)); } if (fileStream is null) { throw new ArgumentNullException(nameof(fileStream)); } using (var pdfDocument = new Document(fileStream)) { var page = pdfDocument.Pages[1]; var pdfFileInfo = new PdfFileInfo(pdfDocument); double pageWidth = page.Rect.Width; double pageHeight = page.Rect.Height; // Вычисляем координаты первого изображения штампов электронной подписи var xIndent = pdfFileInfo.GetPageWidth(1) / pageWidth * PagePadding; var yIndent = pdfFileInfo.GetPageHeight(1) / pageHeight * PagePadding; // Максимальная высота изображения штампа в текущей строке (нужна для выравнивания изображений в строке) double maxImageHeight = 0; foreach (var imageHelper in images.Select(x => new ImageHelper(x))) { // Если верхняя левая координата текущего изображения больше высоты страницы PDF-документа, // то прекращаем вставку изображений if (yIndent + imageHelper.Height > pageHeight) { break; } // Если ширина строки вставленных изображений превышает ширину страницы, // то переходим на следующую строку if (xIndent + imageHelper.Width > pageWidth) { yIndent += maxImageHeight + ImageMargin; xIndent = PagePadding; maxImageHeight = imageHelper.Height; } // В противном случае вычисляем максимальную высоту изображения штампа в текущей строке else if (imageHelper.Height > maxImageHeight) { maxImageHeight = imageHelper.Height; } // Вставляем текущее изображение по указанным координатам InsertImage(page, imageHelper, xIndent, yIndent); // Вычисляем горизонтальную координату следующего изображения xIndent += imageHelper.Width + ImageMargin; } // Копируем в поток сформированный PDF-файл со вставленными изображениями штампов электронной подписи var outputStream = new MemoryStream(); pdfDocument.Save(outputStream); outputStream.Seek(0, SeekOrigin.Begin); return(new GeneratedFileInfo { Stream = outputStream }); } }
public bool isFileProtected(MemoryStream file) { PdfFileInfo info = new PdfFileInfo(file); return(info.IsEncrypted); }
public ActionResult <Response> ConcatenateWithContents([FromBody] Request request) { try { Stopwatch stopwatch1 = new Stopwatch(); stopwatch1.Start(); PdfFileEditor pdfEditor = new PdfFileEditor(); using (MemoryStream Concatenated_Stream = new MemoryStream()) { string concFilename = "Concatenated_Table_Of_Contents.pdf"; List <System.IO.Stream> pdfStreams = new List <System.IO.Stream>(); string[] files = System.IO.Directory.GetFiles(serverDirectory); foreach (string file in files) { if (file.ToLower().Contains(concFilename.ToLower())) { continue; } if (!Path.GetExtension(file).Equals(".pdf")) { continue; } System.IO.FileStream stream = new System.IO.FileStream(file, System.IO.FileMode.Open); pdfStreams.Add(stream); } //System.IO.FileStream outputPDF = new System.IO.FileStream(serverDirectory + request.filename + ".pdf", System.IO.FileMode.Create); Stopwatch stopwatch2 = new Stopwatch(); stopwatch2.Start(); pdfEditor.Concatenate(pdfStreams.ToArray(), Concatenated_Stream); stopwatch2.Stop(); Console.WriteLine("PdfEditor.Concatenate Action: " + stopwatch2.ElapsedMilliseconds.ToString()); // Insert a blank page at the begining of concatenated file to display Table of Contents Aspose.Pdf.Document concatenated_pdfDocument = new Aspose.Pdf.Document(Concatenated_Stream); // Insert a empty page in a PDF concatenated_pdfDocument.Pages.Insert(1); using (MemoryStream Document_With_BlankPage = new MemoryStream()) { // Save output file stopwatch2.Reset(); stopwatch2.Start(); concatenated_pdfDocument.Save(Document_With_BlankPage); stopwatch2.Stop(); Console.WriteLine("Concatenated_pdfDocument.Save Action: " + stopwatch2.ElapsedMilliseconds.ToString()); using (var Document_with_TOC_Heading = new MemoryStream()) { // Add Table Of Contents logo as stamp to PDF file PdfFileStamp fileStamp = new PdfFileStamp(); // Find the input file fileStamp.BindPdf(Document_With_BlankPage); // Set Text Stamp to display string Table Of Contents Aspose.Pdf.Facades.Stamp stamp = new Aspose.Pdf.Facades.Stamp(); stamp.BindLogo(new FormattedText("Table Of Contents", System.Drawing.Color.Maroon, System.Drawing.Color.Transparent, Aspose.Pdf.Facades.FontStyle.Helvetica, EncodingType.Winansi, true, 18)); // Specify the origin of Stamp. We are getting the page width and specifying the X coordinate for stamp stamp.SetOrigin((new PdfFileInfo(Document_With_BlankPage).GetPageWidth(1) / 3), 700); // Set particular pages stamp.Pages = new int[] { 1 }; // Add stamp to PDF file stopwatch2.Reset(); stopwatch2.Start(); fileStamp.AddStamp(stamp); stopwatch2.Stop(); Console.WriteLine("FileStamp.AddStamp Action: " + stopwatch2.ElapsedMilliseconds.ToString()); int counter = 1; int diff = 0; foreach (System.IO.Stream stream in pdfStreams) { var Document_Link = new Aspose.Pdf.Facades.Stamp(); Document_Link.BindLogo(new FormattedText(counter + " - Link to Document " + counter, System.Drawing.Color.Black, System.Drawing.Color.Transparent, Aspose.Pdf.Facades.FontStyle.Helvetica, EncodingType.Winansi, true, 12)); Document_Link.SetOrigin(150, 650 - diff); Document_Link.Pages = new int[] { 1 }; fileStamp.AddStamp(Document_Link); counter++; diff += 40; } stopwatch2.Reset(); stopwatch2.Start(); fileStamp.Save(Document_with_TOC_Heading); stopwatch2.Stop(); Console.WriteLine("FileStamp.Save Action: " + stopwatch2.ElapsedMilliseconds.ToString()); fileStamp.Close(); PdfContentEditor contentEditor = new PdfContentEditor(); // Bind the PDF file in which we added the blank page contentEditor.BindPdf(Document_with_TOC_Heading); counter = 1; diff = 0; int numberOfpagesOfPreviousFile = 0; foreach (System.IO.Stream stream in pdfStreams) { if (counter == 1) { contentEditor.CreateLocalLink(new System.Drawing.Rectangle(150, 650 - diff, 100, 20), counter + 1, 1, System.Drawing.Color.Transparent); } else { //Replace counter with numberOfpagesOfPreviousFile of the following line to fix Link page number contentEditor.CreateLocalLink(new System.Drawing.Rectangle(150, 650 - diff, 100, 20), counter + 1, 1, System.Drawing.Color.Transparent); } counter++; numberOfpagesOfPreviousFile = new PdfFileInfo(stream).NumberOfPages; diff += 40; } if (System.IO.File.Exists(serverDirectory + concFilename)) { System.IO.File.Delete(serverDirectory + concFilename); } stopwatch2.Reset(); stopwatch2.Start(); contentEditor.Save(serverDirectory + concFilename); stopwatch2.Stop(); Console.WriteLine("FileStamp.Save Action: " + stopwatch2.ElapsedMilliseconds.ToString()); } } } stopwatch1.Stop(); Console.WriteLine("Total Time: " + stopwatch1.ElapsedMilliseconds.ToString()); return(new Response() { FileContent = string.Empty, FileName = "Concatenated_Table_Of_Contents.pdf", Message = "Files Concatenated successfully to: Concatenated_Table_Of_Contents.pdf file", Success = true }); } catch (Exception ex) { return(new Response() { FileContent = string.Empty, FileName = "", Message = "Could not concatenate files. " + ex.Message, Success = false }); } }
public void Process() { this.Options.Validate(); DirectoryInfo RootOutputDirectoryInfo = new DirectoryInfo(this.Options.OutputDirectory); DirectoryInfo RootHl7v2OutputDirectory = new DirectoryInfo(Path.Combine(RootOutputDirectoryInfo.FullName, "HL7v2 Messages")); DirectoryInfo RootPdfDirectory = new DirectoryInfo(Options.PdfAttachmentInputDirectory); DirectoryInfo RootReportDataDirectory = new DirectoryInfo(Options.LogicalModelInputDirectory); DirectoryInfo RootFhirOutputDirectory = new DirectoryInfo(Path.Combine(RootOutputDirectoryInfo.FullName, "FHIR Bundles (experimental)")); DirectoryInfo RootCdaPackagesOutputDirectory = new DirectoryInfo(Path.Combine(RootOutputDirectoryInfo.FullName, "CDA Packages")); DirectoryInfo RootCdaDocumentOutputDirectory = new DirectoryInfo(Path.Combine(RootOutputDirectoryInfo.FullName, "CDA Documents")); DirectoryInfo TempWorkingCDADocumentDirectoryInfo = new System.IO.DirectoryInfo(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "CdaGeneratorWorkingDirectory\\CDADocuments")); List <PathologyReportContainer> PathologyReportContainerList = new List <PathologyReportContainer>(); //If below is true we generate the Pathology Data json files from the hard coded source. if (this.Options.GenerateLogicalModels) { WriteLine("----------------------------------------------------------------------"); WriteLine($"The option {nameof(this.Options.GenerateLogicalModels)} is set to True."); WriteLine("Generate Pathology Report Data files"); //Validate that the folder where we will output the generated LogicalModle files to is empty, as we do not want to overwrite files they may have created. RootReportDataDirectory.CreateDirectoryIfNoExist(); RootReportDataDirectory = new DirectoryInfo(Options.LogicalModelInputDirectory); if (RootReportDataDirectory.GetFiles("*.json", SearchOption.TopDirectoryOnly).Count() > 0) { throw new ApplicationException($"The {RootReportDataDirectory.FullName} directory must empty when {nameof(this.Options.GenerateLogicalModels)} is set to true."); } //Validate that the folder where we will output the PDF files to is empty, as we do not want to overwrite files they may have created. RootPdfDirectory.CreateDirectoryIfNoExist(); RootPdfDirectory = new DirectoryInfo(Options.PdfAttachmentInputDirectory); if (RootPdfDirectory.GetFiles("*.pdf", SearchOption.TopDirectoryOnly).Count() > 0) { throw new ApplicationException($"The {RootPdfDirectory.FullName} directory must empty when {nameof(this.Options.GenerateLogicalModels)} is set to true."); } DirectoryInfo StaticApplicationPdfDiectory = GetApplicationPdfDirectory(); foreach (FileInfo PdfFileInfo in StaticApplicationPdfDiectory.GetFiles("*.pdf", SearchOption.TopDirectoryOnly)) { PdfFileInfo.CopyTo(Path.Combine(RootPdfDirectory.FullName, PdfFileInfo.Name)); } var SpiaPathologyReportFactory = new Spia.PathologyReportModel.Factory.SpiaPathologyReportFactory(); PathologyReportContainerList = SpiaPathologyReportFactory.GetAll(); foreach (var PathologyReportContainer in PathologyReportContainerList) { FileInfo JsonFilePath = new FileInfo($@"{RootReportDataDirectory.FullName}\{PathologyReportContainer.PathologyReport.PdfFileName.Replace(".pdf", ".json")}"); WriteLine(JsonFilePath.Name); var Writer = new Spia.PathologyReportModel.JsonFileGenerator(); Writer.Write(PathologyReportContainer, JsonFilePath.FullName); //Test we can read it back it without error var Reader = new Spia.PathologyReportModel.JsonFileReader(); var PathologyReportsRead = Reader.ReadPathologyReports(JsonFilePath.FullName); } PathologyReportContainerList.Clear(); } //Read in all Pathology Data json files found in the directory WriteLine("----------------------------------------------------------------------"); WriteLine("Reading in Pathology Report Logical Model files"); WriteLine($"Input Directory: {RootReportDataDirectory.FullName}"); if (!RootReportDataDirectory.Exists) { throw new ApplicationException($"The Pathology Report Logical Model folder does not exist at :{RootReportDataDirectory.FullName}"); } FileInfo[] ReportDataFileInfoArray = RootReportDataDirectory.GetFiles("*.json", SearchOption.TopDirectoryOnly); if (ReportDataFileInfoArray.Count() == 0) { throw new ApplicationException($"The Pathology Report Logical Model folder contains no Logical Model .json files."); } foreach (FileInfo ReportDataFileInfo in RootReportDataDirectory.GetFiles("*.json", SearchOption.TopDirectoryOnly)) { var Reader = new Spia.PathologyReportModel.JsonFileReader(); try { WriteLine(ReportDataFileInfo.Name); var PathologyReportsRead = Reader.ReadPathologyReports(ReportDataFileInfo.FullName); PathologyReportContainerList.Add(PathologyReportsRead); } catch (Exception Exec) { WriteLine($"The Pathology Report Logical Model for file name {ReportDataFileInfo.Name} had the following issue:"); throw Exec; } } if (Options.GenerateHL7Version2Messages) { //Validation for HL7 v2 foreach (PathologyReportContainer PathologyReportContainer in PathologyReportContainerList) { var ErrorMessageList = new List <string>(); if (!PathologyReportContainer.IsValid(PathologyReportContainer, PathologyReportModel.CustomAttribute.ScopeType.Hl7v2, ErrorMessageList)) { StringBuilder sb = new StringBuilder("HL7 v2 validation errors where detected:\n"); ErrorMessageList.ForEach(x => sb.Append(x + "\n")); throw new ApplicationException(sb.ToString());; } } RootHl7v2OutputDirectory.CreateDirectoryIfNoExist(); RootHl7v2OutputDirectory.DeleteAllFileAndDirectories(); //Generate HL7 v2 Messages for each Pathology Data json file WriteLine("----------------------------------------------------------------------"); WriteLine("Generate HL7 v2 Messages"); WriteLine($"Output Directory: {RootHl7v2OutputDirectory.FullName}"); foreach (PathologyReportContainer PathologyReportContainer in PathologyReportContainerList) { string HL7Message = MessageFactory.GetMessage(PathologyReportContainer.PathologyReport, RootPdfDirectory.FullName); FileInfo HL7MessageFileInfo = new FileInfo($@"{RootHl7v2OutputDirectory}\{PathologyReportContainer.PathologyReport.PdfFileName.Replace(".pdf", ".hl7")}"); File.WriteAllText(HL7MessageFileInfo.FullName, HL7Message); WriteLine(HL7MessageFileInfo.Name); } } if (Options.GenerateFhirBundles) { //Generate FHIR Bundles WriteLine("----------------------------------------------------------------------"); WriteLine("Generate FHIR Bundles"); WriteLine($"Output Directory: {RootFhirOutputDirectory.FullName}"); RootFhirOutputDirectory.CreateDirectoryIfNoExist(); RootFhirOutputDirectory.DeleteAllFileAndDirectories(); FhirPathologyFactory PathologyFactory = new FhirPathologyFactory(); foreach (PathologyReportContainer PathologyReportContainer in PathologyReportContainerList) { string PdfFileName = PathologyReportContainer.PathologyReport.PdfFileName; FileInfo FhirBundleFilkeInfo = new FileInfo(Path.Combine(RootFhirOutputDirectory.FullName, PdfFileName.Replace(".pdf", ".json"))); string Resource = PathologyFactory.CreateJson(PathologyReportContainer, RootPdfDirectory.FullName); File.WriteAllText(FhirBundleFilkeInfo.FullName, Resource); WriteLine($"{FhirBundleFilkeInfo.Name}"); } } DirectoryInfo CurrentCDADocuementDirectoryInfo = null; byte[] Logo = null; //Generate CDA Documents if (Options.GenerateCdaDocuments || Options.GenerateCdaPackages) { //Get the Logo and convert to Byte array ImageConverter converter = new ImageConverter(); Logo = (byte[])converter.ConvertTo(Resource.RCPA_PITUS_Logo, typeof(byte[])); if (!Options.GenerateCdaDocuments) { CurrentCDADocuementDirectoryInfo = TempWorkingCDADocumentDirectoryInfo; } else { CurrentCDADocuementDirectoryInfo = RootCdaDocumentOutputDirectory; } CurrentCDADocuementDirectoryInfo.CreateDirectoryIfNoExist(); CurrentCDADocuementDirectoryInfo.DeleteAllFileAndDirectories(); //Generate HL7 v2 Messages for each Pathology Data json file if (Options.GenerateCdaDocuments) { WriteLine("----------------------------------------------------------------------"); WriteLine($"Generate CDA Documents"); WriteLine($"Output Directory: {CurrentCDADocuementDirectoryInfo.FullName}"); } else { WriteLine("----------------------------------------------------------------------"); WriteLine($"Temporarily generate CDA Documents for CDA Packaging"); } //Validation for CDA foreach (PathologyReportContainer PathologyReportContainer in PathologyReportContainerList) { var ErrorMessageList = new List <string>(); if (!PathologyReportContainer.IsValid(PathologyReportContainer, PathologyReportModel.CustomAttribute.ScopeType.Cda, ErrorMessageList)) { StringBuilder sb = new StringBuilder("CDA validation errors where detected:\n"); ErrorMessageList.ForEach(x => sb.Append(x + "\n")); throw new ApplicationException(sb.ToString());; } } foreach (PathologyReportContainer PathologyReportContainer in PathologyReportContainerList) { var FileName = PathologyReportContainer.PathologyReport.PdfFileName; AdhaCdaFileGenerator CdaDocument = new AdhaCdaFileGenerator(); CdaDocument.LogEventMessageDelegate = SpiaFileGenerator.WriteLine; CdaDocument.Process(PathologyReportContainer, RootPdfDirectory.FullName, CurrentCDADocuementDirectoryInfo.FullName, Logo); } } //Generate CDA Package if (Options.GenerateCdaPackages) { WriteLine("----------------------------------------------------------------------"); WriteLine($"Generate CDA Packages"); WriteLine($"Output Directory: {RootCdaPackagesOutputDirectory.FullName}"); AdhaCdaPackageFileGenerator CdaPackager = new AdhaCdaPackageFileGenerator(Options.NashCertificateSerial); RootCdaPackagesOutputDirectory.CreateDirectoryIfNoExist(); RootCdaPackagesOutputDirectory.DeleteAllFiles(".zip"); CdaPackager.LogEventMessageDelegate = SpiaFileGenerator.WriteLine; CdaPackager.Process(Options.CdaPackagerApproverPerson, RootPdfDirectory.FullName, CurrentCDADocuementDirectoryInfo.FullName, RootCdaPackagesOutputDirectory.FullName, Logo); if (!Options.GenerateCdaDocuments) { CurrentCDADocuementDirectoryInfo.DeleteAllFiles(".xml"); } } }