public static void Merge(List <string> filesContents, string filePath) { using (var fileStream = new FileStream(filePath, FileMode.Create)) { using (var document = new Document(PageSize.A4)) { using (var copyWriter = new PdfSmartCopy(document, fileStream)) { document.Open(); copyWriter.RegisterFonts(); foreach (var fileContent in filesContents) { using (var pdfReader = new PdfReader(fileContent)) { copyWriter.AddDocument(pdfReader); } } document.Close(); copyWriter.RegisterProperties(); } } } AddPdfAFlag(filePath); }
public static Byte[] GetMultipleReports(ReportBase reportPara, List <ListOfSelected> myList) { Document doc = new Document(); MemoryStream msOutput = new MemoryStream(); PdfCopy pCopy = new PdfSmartCopy(doc, msOutput); // using iTextSharp pdf function doc.Open(); foreach (var item in myList) { try { Byte[] myPDF = GetOneReport(reportPara, item); // item => ListOFSelected if (myPDF.Length > 10) { AddFileToPCopy(ref pCopy, myPDF); } } catch { } } try { pCopy.Close(); doc.Close(); } catch { } return(msOutput.ToArray()); }
public static byte[] Merge(string[] documentPaths) { byte[] mergedDocument; using (MemoryStream memoryStream = new MemoryStream()) using (Document document = new Document()) { PdfSmartCopy pdfSmartCopy = new PdfSmartCopy(document, memoryStream); document.Open(); foreach (string docPath in documentPaths) { PdfReader reader = new PdfReader(docPath); try { reader.ConsolidateNamedDestinations(); int numberOfPages = reader.NumberOfPages; for (int page = 0; page < numberOfPages;) { PdfImportedPage pdfImportedPage = pdfSmartCopy.GetImportedPage(reader, ++page); pdfSmartCopy.AddPage(pdfImportedPage); } } finally { reader.Close(); } } document.Close(); mergedDocument = memoryStream.ToArray(); } return(mergedDocument); }
private void init() { _document = new Document(); _writer = new PdfSmartCopy(_document, OutputFileStream); _writer.SetFullCompression(); _document.Open(); }
/// <summary> /// Merges the PDFS. /// </summary> /// <param name="pdfsToMerge">The PDFS to merge.</param> /// <returns>The merged PDF's resulting bytes.</returns> public byte[] MergePdfs(IEnumerable <byte[]> pdfsToMerge) { using (MemoryStream ms = new MemoryStream()) { using (Document doc = new Document()) { using (PdfSmartCopy copy = new PdfSmartCopy(doc, ms)) { doc.Open(); // Loop through each byte array foreach (byte[] p in pdfsToMerge) { // Create a PdfReader bound to that byte array using (PdfReader reader = new PdfReader(p)) { // Add the entire document instead of page-by-page copy.AddDocument(reader); } } doc.Close(); } } // Return just before disposing return(ms.ToArray()); } }
public MemoryStream MergePdfForms(List <byte[]> files) { if (files.Count > 1) { PdfReader pdfFile; Document doc; PdfWriter pCopy; MemoryStream msOutput = new MemoryStream(); pdfFile = new PdfReader(files[0]); doc = new Document(); pCopy = new PdfSmartCopy(doc, msOutput); doc.Open(); for (int k = 0; k < files.Count; k++) { pdfFile = new PdfReader(files[k]); for (int i = 1; i < pdfFile.NumberOfPages + 1; i++) { ((PdfSmartCopy)pCopy).AddPage(pCopy.GetImportedPage(pdfFile, i)); } pCopy.FreeReader(pdfFile); } pdfFile.Close(); pCopy.Close(); doc.Close(); return(msOutput); } else if (files.Count == 1) { return(new MemoryStream(files[0])); } return(null); }
public void concatAndAddContent(List <string> pdfsFile, string sOutputFile) { byte[] result; using (var ms = new MemoryStream()) { using (var doc = new Document()) { using (var copy = new PdfSmartCopy(doc, ms)) { doc.Open(); foreach (var item in pdfsFile) { using (var reader = new PdfReader(item)) { copy.AddDocument(reader); } } doc.Close(); } } result = ms.ToArray(); } using (var fs = new FileStream(sOutputFile, FileMode.Create, FileAccess.Write)) { fs.Write(result, 0, result.Length); } }
/// <summary> /// Creates a single PDF from multiple at a specified location /// </summary> private static void MergePdf() { String result = @"d:\PDF\Output\mergefile.pdf"; Document document = new Document(); //create PdfSmartCopy object PdfSmartCopy copy = new PdfSmartCopy(document, new FileStream(result, FileMode.Create)); copy.SetFullCompression(); //open the document document.Open(); PdfReader reader = null; foreach (var file in new DirectoryInfo(@"D:\PDF\Output").GetFiles("*.pdf").OrderBy(x => x.Name)) { if (file.Name == "mergefile.pdf") { continue; } //create PdfReader object reader = new PdfReader(file.FullName); //merge combine pages for (int page = 1; page <= reader.NumberOfPages; page++) { copy.AddPage(copy.GetImportedPage(reader, page)); } } //close the document object document.Close(); }
public void SmartCopySignedDocuments() { string file = RESOURCES + "hello_signed1.pdf"; Directory.CreateDirectory("PdfCopyTest/"); Document pdfDocument = new Document(); PdfSmartCopy copier = new PdfSmartCopy(pdfDocument, new FileStream("PdfCopyTest/SmartCopySignedDocuments.pdf", FileMode.Create)); pdfDocument.Open(); PdfReader reader1 = new PdfReader(file); copier.AddPage(copier.GetImportedPage(reader1, 1)); copier.FreeReader(reader1); reader1 = new PdfReader(file); copier.AddPage(copier.GetImportedPage(reader1, 1)); copier.FreeReader(reader1); pdfDocument.Close(); PdfReader reader = new PdfReader("PdfCopyTest/SmartCopySignedDocuments.pdf"); PdfDictionary sig = (PdfDictionary)reader.GetPdfObject(8); PdfDictionary sigRef = sig.GetAsArray(PdfName.REFERENCE).GetAsDict(0); Assert.True(PdfName.SIGREF.Equals(sigRef.GetAsName(PdfName.TYPE))); Assert.False(sigRef.Contains(PdfName.DATA)); }
private static byte[] Merge(Collection <byte[]> pdfCollection, Document document, string script) { if (pdfCollection == null) { throw new ArgumentNullException("pdfCollection"); } // get a list of readers for the collection of bytes passed in var readers = pdfCollection.Where(b => b != null).Select(b => new PdfReader(b)).ToList(); var totalPages = readers.Sum(r => r.NumberOfPages); byte[] mergedPdf; using (var stream = new MemoryStream()) { var writer = new PdfSmartCopy(document, stream); document.Open(); var currentPage = 1; readers.ForEach(r => { currentPage = Append(writer, r, document, currentPage, totalPages); }); if (!string.IsNullOrEmpty(script)) { var action = PdfAction.JavaScript(script, writer); writer.AddJavaScript(action); } document.Close(); stream.Flush(); mergedPdf = stream.ToArray(); } return(mergedPdf); }
public void Merge(List <string> inputfiles) { inputfiles.Sort(); var outputpath = FileUtilities.GetOutputPath(inputfiles.First(), Libraries.CommonUtilities.Models.ActionType.MERGE); Document doc = null; PdfSmartCopy pdf = null; try { var stream = new FileStream(outputpath, FileMode.Create); doc = new Document(); pdf = new PdfSmartCopy(doc, stream); doc.Open(); foreach (string file in inputfiles) { pdf.AddDocument(new PdfReader(file)); } Console.WriteLine("Merged {0} into {1}", inputfiles.Count, Path.GetFileName(outputpath)); } catch (Exception) { } finally { pdf?.Dispose(); doc?.Dispose(); } }
public static byte[] concatAndAddContent(List <byte[]> pdfByteContent) { using (var ms = new MemoryStream()) { using (var doc = new Document()) { using (var copy = new PdfSmartCopy(doc, ms)) { doc.Open(); //Loop through each byte array foreach (var p in pdfByteContent) { //Create a PdfReader bound to that byte array using (var reader = new PdfReader(p)) { //Add the entire document instead of page-by-page copy.AddDocument(reader); } } doc.Close(); } } //Return just before disposing return(ms.ToArray()); } }
//======================================== // // //======================================== private void ExtractAndSaveFile(string sourcePdfFilePath, string outpuPdfFileName, int startPage, int numberOfPages) { using (PdfReader reader = new PdfReader(sourcePdfFilePath)) { Document document = new Document(); PdfSmartCopy partial = new PdfSmartCopy(document, new FileStream(outpuPdfFileName, FileMode.Create)); partial.SetPdfVersion(PdfWriter.PDF_VERSION_1_5); partial.CompressionLevel = PdfStream.BEST_COMPRESSION; partial.SetFullCompression(); document.Open(); for (int pagenumber = startPage; pagenumber < (startPage + numberOfPages); pagenumber++) { if (reader.NumberOfPages >= pagenumber) { partial.AddPage(partial.GetImportedPage(reader, pagenumber)); } else { break; } } document.Close(); } }
public static void ShowPDFWithItxt(Byte[] pdfDocument) { HttpContext.Current.Response.ContentType = "application/pdf"; HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=IEP_Report.pdf"); HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); Document doc = new Document(); MemoryStream msOutput = new MemoryStream(pdfDocument); // PdfCopy pCopy; PdfCopy pCopy = new PdfSmartCopy(doc, msOutput); doc.Open(); MemoryStream stream1 = new MemoryStream(pdfDocument); MemoryStream output = new MemoryStream(); PdfReader input = new PdfReader(stream1.ToArray()); var pdfDoc = new Document(); PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream); pdfDoc.Open(); pdfDoc.Close(); HttpContext.Current.Response.Write(pdfDoc); HttpContext.Current.Response.End(); }
public static byte[] Merge(List <byte[]> filesContents) { using (var memoryStream = new MemoryStream()) { using (var document = new Document(PageSize.A4)) { using (var copyWriter = new PdfSmartCopy(document, memoryStream)) { document.Open(); copyWriter.RegisterFonts(); foreach (var fileContent in filesContents) { using (var pdfReader = new PdfReader(fileContent)) { copyWriter.AddDocument(pdfReader); } } document.Close(); copyWriter.RegisterProperties(); } } return(AddPdfAFlag(memoryStream.ToArray())); } }
/** * Test to make sure that the following issue is fixed: http://sourceforge.net/mailarchive/message.php?msg_id=30891213 */ virtual public void TestDecodeParmsArrayWithNullItems() { Document document = new Document(); MemoryStream byteStream = new MemoryStream(); PdfSmartCopy pdfSmartCopy = new PdfSmartCopy(document, byteStream); document.Open(); PdfReader reader = TestResourceUtils.GetResourceAsPdfReader(RESOURCES, "imgWithDecodeParms.pdf"); pdfSmartCopy.AddPage(pdfSmartCopy.GetImportedPage(reader, 1)); document.Close(); reader.Close(); reader = new PdfReader(byteStream.ToArray()); PdfDictionary page = reader.GetPageN(1); PdfDictionary resources = page.GetAsDict(PdfName.RESOURCES); PdfDictionary xObject = resources.GetAsDict(PdfName.XOBJECT); PdfStream img = xObject.GetAsStream(new PdfName("Im0")); PdfArray decodeParms = img.GetAsArray(PdfName.DECODEPARMS); Assert.AreEqual(2, decodeParms.Size); Assert.IsTrue(decodeParms[0] is PdfNull); reader.Close(); }
public static void ConcatPages(List <PdfActionResult> docs, string outputFilePath, Rectangle pageSize) { try { // Capture the correct size and orientation for the page: using (var resultDoc = new Document(pageSize)) using (var fs = new FileStream(outputFilePath, FileMode.Create)) using (var pdfCopy = new PdfSmartCopy(resultDoc, fs)) { resultDoc.Open(); foreach (var doc in docs) { using (PdfReader reader = new PdfReader(doc.ResultPdfPath)) { PdfImportedPage importedPage = pdfCopy.GetImportedPage(reader, doc.Action.ModelPageIndex); pdfCopy.AddPage(importedPage); } } } } catch (Exception ex) { throw new Exception("Impossible to concatenate Pages", ex); } }
/// <summary> /// 合并生成的pdf文件流 /// </summary> /// <param name="pdfStreams">多个pdf文件字节</param> /// <returns>返回合并之后的pdf文件流</returns> public static MemoryStream MergePdfs(List <byte[]> pdfStreams) { try { Document document = new Document(); MemoryStream mergePdfStream = new MemoryStream(); //这里用的是smartCopy,整篇文档只会导入一份字体。属于可接受范围内 PdfSmartCopy copy = new PdfSmartCopy(document, mergePdfStream); document.Open(); for (int i = 0; i < pdfStreams.Count; i++) { byte[] stream = pdfStreams[i]; PdfReader reader = new PdfReader(stream); //for循环新增文档页数,并copy pdf数据 document.NewPage(); PdfImportedPage imported = copy.GetImportedPage(reader, 1); copy.AddPage(imported); reader.Close(); } copy.Close(); document.Close(); return(mergePdfStream); } catch (Exception ex) { ex.ToString(); return(null); } }
//2.1 //Form different-PDF-File with different subgroup and country except group E letters ___________________________ 2.1 private void PrintGroupWithCountry(string inputHead, string outputPDFFile, string LtrSubGrp, string PtnCNY, string pageFlag) //pageFlag is single or double page (PDF output) : A,B,C,D letters { //按AS400系統的短訊語言分別生成中文或葡文信函 (SMS Lang. C=中文信, P=葡文信) //- 如沒有語言選項,且只有葡文姓名,同時生成中文及葡文信 (2 letters 中及葡文信) //- 承上點,即如果沒有語言選項但有中文姓名,生成中文信 (1 letter 中文信) var ABCD_Group_List = GlobalVar.FPL1LTR_List.Where(grp => grp.LTRSUBGRP.Trim() == LtrSubGrp && grp.PTNCNY.Trim() == PtnCNY && grp.PAGE == pageFlag).ToList(); int idx = 0; //has data if (ABCD_Group_List.Count() > 0) { using (iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.A4)) { string prefix_breakPage = ""; prefix_breakPage = ABCD_Group_List.Count() > 5000 ? textBoxFrom.Text + "_" : ""; // Create a PdfStreamWriter instance, responsible to write the document into the specified file using (var fs = new FileStream(GlobalVar.wPATH() + prefix_breakPage + outputPDFFile, FileMode.Create)) //output result PDF file { using (var copy = new PdfSmartCopy(doc, fs)) { doc.Open(); foreach (var pageInfo in ABCD_Group_List) //passing Subgroup and Country-code for reading data (A or B or C or D group list with diff. country) { idx++; if (pageInfo.PAGE == "2") //double-page { FillTextToPDF_CHN("inCHN_" + outputPDFFile, copy, pageInfo, LtrSubGrp, PtnCNY); //chinese version (rename output filename to input file name) inCHN_xxx FillTextToPDF_POR("inPOR_" + outputPDFFile, copy, pageInfo, LtrSubGrp, PtnCNY); //portuguese version (rename output filename to input file name) inPOR_xxx } else { if (pageInfo.PTSLNG.Trim() == "C") //Chinese { FillTextToPDF_CHN("inCHN_" + outputPDFFile, copy, pageInfo, LtrSubGrp, PtnCNY); //chinese version } else if (pageInfo.PTSLNG.Trim() == "P") //Portuguese { FillTextToPDF_POR("inPOR_" + outputPDFFile, copy, pageInfo, LtrSubGrp, PtnCNY); //portuguese version } else if (pageInfo.PTNCNA.Trim() != "") //沒有PTSLNG, 如有中文名 //Chinese letter { FillTextToPDF_CHN("inCHN_" + outputPDFFile, copy, pageInfo, LtrSubGrp, PtnCNY); //chinese version } } if (idx % 500 == 0) { Console.WriteLine(idx.ToString() + " " + pageInfo.LTRNO + " === " + DateTime.Now.ToString()); } } } //end of copy } } } }
public MemoryStream MergePdfForms(List <byte[]> files) { if (files.Count > 1) { string[] names; PdfStamper stamper; MemoryStream msTemp = null; PdfReader pdfTemplate = null; PdfReader pdfFile; Document doc; PdfWriter pCopy; var msOutput = new MemoryStream(); pdfFile = new PdfReader(files[0]); doc = new Document(); pCopy = new PdfSmartCopy(doc, msOutput) { PdfVersion = PdfWriter.VERSION_1_7 }; doc.Open(); for (var k = 0; k < files.Count; k++) { for (var i = 1; i < pdfFile.NumberOfPages + 1; i++) { msTemp = new MemoryStream(); pdfTemplate = new PdfReader(files[k]); stamper = new PdfStamper(pdfTemplate, msTemp); names = new string[stamper.AcroFields.Fields.Keys.Count]; stamper.AcroFields.Fields.Keys.CopyTo(names, 0); foreach (var name in names) { stamper.AcroFields.RenameField(name, name + "_file" + k.ToString()); } stamper.Close(); pdfFile = new PdfReader(msTemp.ToArray()); ((PdfSmartCopy)pCopy).AddPage(pCopy.GetImportedPage(pdfFile, i)); pCopy.FreeReader(pdfFile); } } pdfFile.Close(); pCopy.Close(); doc.Close(); return(msOutput); } else if (files.Count == 1) { return(new MemoryStream(files[0])); } return(null); }
public static void appendSignaturePage(PdfSmartCopy copy, byte[] signaturePage, byte[] signature, String signingOfficerName, String signingOfficerTitle) { using (var second_ms = new MemoryStream()) { PdfReader pdfr = new PdfReader(signaturePage); PdfStamper pdfs = new PdfStamper(pdfr, second_ms); Image image = iTextSharp.text.Image.GetInstance(signature); Rectangle rect; PdfContentByte content; rect = pdfr.GetPageSize(1); content = pdfs.GetOverContent(1); image.SetAbsolutePosition(84.0F, 475.0F); image.ScalePercent(29.0F, 25.0F); content.AddImage(image); PdfLayer layer = new PdfLayer("info-layer", pdfs.Writer); content.BeginLayer(layer); content.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 20); String[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; DateTime today = DateTime.Now; String monthString = months[today.Month - 1]; String yearString = today.Year.ToString().Substring(2); var now = DateTime.Now; String daySuffix = (now.Day % 10 == 1 && now.Day != 11) ? "st" : (now.Day % 10 == 2 && now.Day != 12) ? "nd" : (now.Day % 10 == 3 && now.Day != 13) ? "rd" : "th"; String dayString = today.Day.ToString() + daySuffix; content.SetColorFill(BaseColor.BLACK); content.BeginText(); content.SetFontAndSize(BaseFont.CreateFont(), 9); content.ShowTextAligned(PdfContentByte.ALIGN_LEFT, signingOfficerName, 84.0F, 420.0F, 0.0F); content.ShowTextAligned(PdfContentByte.ALIGN_LEFT, signingOfficerTitle, 84.0F, 370.0F, 0.0F); content.ShowTextAligned(PdfContentByte.ALIGN_LEFT, dayString, 152.0F, 624.0F, 0.0F); content.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, monthString, 285.0F, 624.0F, 0.0F); content.ShowTextAligned(PdfContentByte.ALIGN_LEFT, yearString, 304.0F, 624.5F, 0.0F); content.EndText(); content.EndLayer(); pdfs.Close(); using (var reader = new PdfReader(second_ms.ToArray())) { //Add the entire document instead of page-by-page copy.AddDocument(reader); } } }
public bool Split(Stream os, long sizeInBytes) { if (!HasMorePages()) { os.Close(); return(false); } overSized = false; Document document = new Document(); PdfCopy copy = new PdfSmartCopy(document, os); document.Open(); bool hasPage = false; PdfResourceCounter counter = new PdfResourceCounter(reader.Trailer); long trailer = counter.GetLength(null); IDictionary <int, PdfObject> resources = counter.Resources; long length = 0; long page; while (HasMorePages()) { counter = new PdfResourceCounter(reader.GetPageN(currentPage)); page = counter.GetLength(resources); resources = counter.Resources; length += page + trailer + XrefLength(resources.Count); if (LOGGER.IsLogging(Level.INFO)) { LOGGER.Info(String.Format("Page {0}: Comparing {1} with {2}", currentPage, length, sizeInBytes)); LOGGER.Info(String.Format(" page {0} trailer {1} xref {2}", page, trailer, XrefLength(resources.Count))); } if (!hasPage || length < sizeInBytes) { hasPage = true; copy.AddPage(copy.GetImportedPage(reader, currentPage)); length = copy.Os.Counter; if (LOGGER.IsLogging(Level.INFO)) { LOGGER.Info(String.Format("Size after adding page: {0}", length)); } if (length > sizeInBytes) { overSized = true; } currentPage++; } else { LOGGER.Info("Page doesn't fit"); break; } } document.Close(); return(true); }
/// <summary> /// <para>(ESP) Este metodo es recursivo, se encarga de asignar los bookmarks y asignarles su parent</para> /// <para>(ENG) this method is recursive, assign the parent for each file</para> /// </summary> /// <param name="doc"> /// <para>(ESP) Este es el documento actual</para> /// <para>(ENG) this is the current document</para> /// </param> /// <param name="pdfCopy"> /// <para>(ESP)es el documento que hará el smart copy</para> /// <para>(ENG) this is the pdfsmartcopy for the append another pdf</para> /// </param> /// <param name="marcadorNombreLibro"> /// <para>(ESP) este es el parent</para> /// <para>(ENG) this is the parent</para> /// </param> /// <param name="enlace"> /// <para>(ESP) Esta es la estructura del documento, donde contiene nombre y url del documento</para> /// <para>(ENG) This is the structure's document, this contains the name and url's file </para> /// </param> /// <param name="rutaPDFs"> /// <para>(ESP)Es donde se generan los documentos</para> /// <para>(ENG)Its the path for create the files</para> /// </param> public static void GenerarHijosEstructura(Document doc, PdfSmartCopy pdfCopy, PdfOutline marcadorNombreLibro, Modelo.POCOs.EstructuraPDF enlace, string rutaPDFs) { try { PdfContentByte pb = pdfCopy.DirectContent; //Crea el link para la sección Anchor section1 = new Anchor(enlace.Nombre) { Name = enlace.Nombre }; Paragraph psecton1 = new Paragraph(); psecton1.Add(section1); //mostrar la sección 1 en una ubicación específica del documento ColumnText.ShowTextAligned(pb, Element.ALIGN_LEFT, psecton1, 36, PageSize.A4.Height - 100, 0); //(ESP) Se crea el marcador para este documento, se hace referencia al documento padre (parent) //(ENG) create the bookmark for this document, and create the reference with the parent var mbot = new PdfOutline(marcadorNombreLibro, PdfAction.GotoLocalPage(enlace.Nombre, false), enlace.Nombre); //(ESP) Se lee el documento //(ENG) read the file PdfReader reader = new PdfReader(enlace.UrlDocumento); //(ESP) Se adjuntan las paginas al documento //(ENG) Copy each page in the current pdfcopy for (int I = 1; I <= reader.NumberOfPages; I++) { doc.SetPageSize(reader.GetPageSizeWithRotation(1)); PdfImportedPage page = pdfCopy.GetImportedPage(reader, I); pdfCopy.AddPage(page); } //Clean up pdfCopy.FreeReader(reader); reader.Close(); if (enlace.Hijos.Any()) { foreach (var cadaHijo in enlace.Hijos) { //(ESP) aquí está la clave, esto es recurisvo //(ENG) this is the magic, its recursive GenerarHijosEstructura(doc, pdfCopy, mbot, cadaHijo, rutaPDFs); } } } catch (Exception error) { } }
public void fillPDF(string templatePath, IEnumerable <IPdfMergeData> mergeDataItems, System.IO.MemoryStream outputstream) { var pagesAll = new List <byte[]>(); byte[] pageBytes = null; foreach (var mergeItem in mergeDataItems) { var templateReader = new iTextSharp.text.pdf.PdfReader(templatePath); using (var tempStream = new System.IO.MemoryStream()) { PdfStamper stamper = new PdfStamper(templateReader, tempStream); stamper.FormFlattening = true; AcroFields fields = stamper.AcroFields; stamper.Writer.CloseStream = false; var fieldVals = mergeItem.MergeFieldValues; foreach (string name in fieldVals.Keys) { fields.SetField(name, fieldVals[name]); } stamper.Close(); tempStream.Position = 0; pageBytes = tempStream.ToArray(); pagesAll.Add(pageBytes); } } Document mainDocument = new Document(PageSize.A4); var pdfCopier = new PdfSmartCopy(mainDocument, outputstream); pdfCopier.CloseStream = false; mainDocument.Open(); foreach (var pageByteArray in pagesAll) { mainDocument.NewPage(); pdfCopier.AddPage(pdfCopier.GetImportedPage(new PdfReader(pageByteArray), 1)); } pdfCopier.Close(); outputstream.Position = 0; }
public static byte[] MergePdfFiles(List <byte[]> pdfFileBytesList, PdfResizeInfo pageSizeInfo, PdfScalingOptions scalingOptions = null) { if (pdfFileBytesList == null || !pdfFileBytesList.Any()) { throw new ArgumentNullException(nameof(pdfFileBytesList), "List of Pdf Files to be merged cannot be null or empty."); } if (pageSizeInfo == null) { throw new ArgumentNullException(nameof(pageSizeInfo), "ResizeInfo cannot be null."); } byte[] outputBytes = null; //NOTE: For Merging we DISABLE ALL SCALING by default, so that we can preserve Annotations, etc. // but this can be easily set by the client code to enable scaling. var pdfScalingOptions = scalingOptions ?? PdfScalingOptions.DisableScaling; //Set static references for Pdf Processing... PdfReader.unethicalreading = pdfScalingOptions.EnableUnethicalReading; Document.Compress = pdfScalingOptions.EnableCompression; var targetPageSize = pageSizeInfo.PageSize; var targetMarginSize = pageSizeInfo.MarginSize; using (var outputMemoryStream = new MemoryStream()) using (var pdfDocBuilder = new Document(targetPageSize, targetMarginSize.Left, targetMarginSize.Right, targetMarginSize.Top, targetMarginSize.Bottom)) using (var pdfSmartCopy = new PdfSmartCopy(pdfDocBuilder, outputMemoryStream)) { pdfDocBuilder.Open(); foreach (var pdfBytes in pdfFileBytesList) { if (pdfScalingOptions.EnableScaling) { var scaledPdfBytes = PdfResizeHelper.ResizePdfPageSize(pdfBytes, pageSizeInfo, pdfScalingOptions); pdfSmartCopy.AppendPdfDocument(scaledPdfBytes); } else { pdfSmartCopy.AppendPdfDocument(pdfBytes); } } pdfDocBuilder.Close(); outputBytes = outputMemoryStream.ToArray(); } return(outputBytes); }
//Burst-- Make each page of an existing multi-page PDF document //as another brand new PDF document private void PDFBurst() { string pdfTemplatePath = Server.MapPath(P_InputStream3); PdfReader reader = new PdfReader(pdfTemplatePath); //PdfCopy copy; PdfSmartCopy copy; for (int i = 1; i < reader.NumberOfPages; i++) { Document d1 = new Document(); copy = new PdfSmartCopy(d1, new FileStream(Server.MapPath(P_OutputStream).Replace(".pdf", i.ToString() + ".pdf"), FileMode.Create)); d1.Open(); copy.AddPage(copy.GetImportedPage(reader, i)); d1.Close(); } }
public static bool Execute(String[] sourcePaths, String targetPath) { try { Console.WriteLine("Begin merging {0} pdf documents . . . ", sourcePaths.Length); byte[] mergedPdf = null; using (MemoryStream ms = new MemoryStream()) { using (Document document = new Document(PageSize.A4, 4, 3, 3, 3)) { using (PdfCopy copy = new PdfSmartCopy(document, ms)) { document.Open(); for (int i = 0; i < sourcePaths.Length; ++i) { Console.WriteLine("Extracting {0} . . . ", sourcePaths[i]); PdfReader reader = new PdfReader(sourcePaths[i]); // loop over the pages in that document int n = reader.NumberOfPages; for (int page = 0; page < n;) { copy.AddPage(copy.GetImportedPage(reader, ++page)); } copy.FreeReader(reader); reader.Close(); } } } mergedPdf = ms.ToArray(); Console.WriteLine(String.Format("Merging {0} bytes of pdf documents", mergedPdf.Length)); using (Stream os = new FileStream(targetPath, FileMode.Create)) { os.Write(mergedPdf, 0, mergedPdf.Length); os.Flush(); } return(true); } } catch (Exception ex) { throw ex; } }
public static byte[] concatAndAddContent(List <byte[]> pdfByteContent, byte[] signaturePage, int signaturePosition, byte[] signature, String signingOfficerName, String signingOfficerTitle) { using (var ms = new MemoryStream()) { using (var doc = new Document()) { using (var copy = new PdfSmartCopy(doc, ms)) { doc.Open(); int index = 0; bool addedSignature = false; //Loop through each byte array foreach (var p in pdfByteContent) { //Create a PdfReader bound to that byte array using (var reader = new PdfReader(p)) { //Add the entire document instead of page-by-page copy.AddDocument(reader); } if (index == signaturePosition && !addedSignature) { appendSignaturePage(copy, signaturePage, signature, signingOfficerName, signingOfficerTitle); addedSignature = true; } ++index; } if (!addedSignature) { appendSignaturePage(copy, signaturePage, signature, signingOfficerName, signingOfficerTitle); addedSignature = true; } doc.Close(); } } //Return just before disposing return(ms.ToArray()); } }
public static void WriteInTemplate(List<Models.Statement> statementList) { try { string invoiceNumber = statementList.FirstOrDefault().Invoice.ToString().Trim(); using (Document document = new Document()) { FileStream fileStream = new FileStream(HostingEnvironment.MapPath("~/Content/reports/" + invoiceNumber + ".pdf"), FileMode.Create); using (PdfSmartCopy smartCopy = new PdfSmartCopy(document, fileStream)) { document.Open(); PdfReader pdfReader = new PdfReader(HostingEnvironment.MapPath("~/Content/InvoiceTemplate/invoiceTemplate.pdf")); using (var memoryStream = new MemoryStream()) { using (PdfStamper pdfStamper = new PdfStamper(pdfReader, memoryStream)) { string month = null; string day = null; string year = null; AcroFields pdfFields = pdfStamper.AcroFields; {//billing address pdfFields.SetField("BillToCompany", statementList.FirstOrDefault().BillToCompany.ToString().Trim().ToUpper()); pdfFields.SetField("BillToContact", statementList.FirstOrDefault().BillToContact.ToString().Trim().ToUpper()); pdfFields.SetField("ShipToCompany", statementList.FirstOrDefault().ShipToCompany.ToString().Trim().ToUpper()); pdfFields.SetField("ShipToContact", statementList.FirstOrDefault().ShipToContact.ToString().Trim().ToUpper()); pdfFields.SetField("PONumber", statementList.FirstOrDefault().PurchaseOrderNo.ToString().Trim()); pdfFields.SetField("OrderNumber", statementList.FirstOrDefault().Order_Number.ToString().Trim()); pdfFields.SetField("ShippingMethod", statementList.FirstOrDefault().Shipping_Method.ToString().Trim()); pdfFields.SetField("PaymentTerms", statementList.FirstOrDefault().Payment_Terms.ToString().Trim()); } pdfStamper.FormFlattening = true; // generate a flat PDF } pdfReader = new PdfReader(memoryStream.ToArray()); smartCopy.AddPage(smartCopy.GetImportedPage(pdfReader, 1)); } } } emailController.CreateMessageWithAttachment(invoiceNumber); } catch (Exception e) { } }
public static byte[] DeletePages(byte[] fileContents, int[] pages) { using (var memoryStream = new MemoryStream()) { using (var document = new Document(PageSize.A4)) { using (var pdfReader = new PdfReader(fileContents)) { pages = pages .Where(o => o >= 1 && o <= pdfReader.NumberOfPages) .Distinct() .ToArray(); if (pages.Length < pdfReader.NumberOfPages) { using (var copyWriter = new PdfSmartCopy(document, memoryStream)) { document.Open(); copyWriter.RegisterFonts(); var contents = copyWriter.DirectContent; for (int i = 1; i <= pdfReader.NumberOfPages; i++) { if (!pages.Contains(i)) { var importedPage = copyWriter.GetImportedPage(pdfReader, i); copyWriter.AddPage(importedPage); } } document.Close(); copyWriter.RegisterProperties(); fileContents = memoryStream.ToArray(); } } } } } return(fileContents); }
public bool Split(Stream os, long sizeInBytes) { if (!HasMorePages()) { os.Close(); return false; } overSized = false; Document document = new Document(); PdfCopy copy = new PdfSmartCopy(document, os); document.Open(); bool hasPage = false; PdfResourceCounter counter = new PdfResourceCounter(reader.Trailer); long trailer = counter.GetLength(null); IDictionary<int, PdfObject> resources = counter.Resources; long length = 0; long page; while (HasMorePages()) { counter = new PdfResourceCounter(reader.GetPageN(currentPage)); page = counter.GetLength(resources); resources = counter.Resources; length += page + trailer + XrefLength(resources.Count); LOGGER.Info(String.Format("Page {0}: Comparing {1} with {2}", currentPage, length, sizeInBytes)); LOGGER.Info(String.Format(" page {0} trailer {1} xref {2}", page, trailer, XrefLength(resources.Count))); if (!hasPage || length < sizeInBytes) { hasPage = true; copy.AddPage(copy.GetImportedPage(reader, currentPage)); length = copy.Os.Counter; LOGGER.Info(String.Format("Size after adding page: {0}", length)); if (length > sizeInBytes) overSized = true; currentPage++; } else { LOGGER.Info("Page doesn't fit"); break; } } document.Close(); return true; }