/// <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); } }
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 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 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); }
private void freeResources() { if (_document == null) { return; } _writer.Close(); _document.Close(); }
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; }
virtual public void XmpEncodingTest() { String fileName = "xmp_UTF-16BE-encoding"; Document document = new Document(); PdfSmartCopy copy = new PdfSmartCopy(document, new FileStream(OUT_FOLDER + fileName, FileMode.Create)); document.Open(); PdfReader reader = new PdfReader(CMP_FOLDER + "pdf_metadata.pdf"); int pageCount = reader.NumberOfPages; for (int currentPage = 1; currentPage <= pageCount; currentPage++) { PdfImportedPage page = copy.GetImportedPage(reader, currentPage); copy.AddPage(page); } MemoryStream os = new MemoryStream(); XmpWriter xmp = new XmpWriter(os, XmpWriter.UTF16, 2000); DublinCoreProperties.AddSubject(xmp.XmpMeta, "Hello World"); DublinCoreProperties.AddSubject(xmp.XmpMeta, "XMP & Metadata"); DublinCoreProperties.AddSubject(xmp.XmpMeta, "Metadata"); xmp.Close(); copy.XmpMetadata = os.ToArray(); string metadataXml = System.Text.Encoding.GetEncoding("UTF-16BE").GetString(copy.XmpMetadata); XmlDocument doc = new XmlDocument(); doc.LoadXml(metadataXml); //<-- This is where the exception is thrown document.Close(); copy.Close(); reader.Close(); }
public static Byte[] MultiplePDF(string[] mySelectIDArray, string reportName, string schoolyear, string schoolcode, string sessionID) { Document doc = new Document(); MemoryStream msOutput = new MemoryStream(); // PdfCopy pCopy; PdfCopy pCopy = new PdfSmartCopy(doc, msOutput); doc.Open(); for (int j = 0; j < mySelectIDArray.Length; j++) { string userID = HttpContext.Current.User.Identity.Name; string employeeID = mySelectIDArray[j].ToString(); if (employeeID != "") { try { Byte[] myPDF; myPDF = GetOneReport(reportName, userID, schoolyear, schoolcode, sessionID); MemoryStream stream1 = new MemoryStream(myPDF); PdfReader pdfFile1 = new PdfReader(stream1.ToArray()); for (int i = 1; i <= pdfFile1.NumberOfPages; i++) { pCopy.AddPage(pCopy.GetImportedPage(pdfFile1, i)); } pdfFile1.Close(); } catch { } } } try { pCopy.Close(); doc.Close(); } catch { } return(msOutput.ToArray()); }
public static byte[] SavePDF(IList <byte[]> Lbyte) { Document document = new Document(); MemoryStream memory = new MemoryStream(); //这里用的是smartCopy,整篇文档只会导入一份字体。属于可接受范围内 PdfSmartCopy copy = new PdfSmartCopy(document, memory); document.Open(); PdfReader reader = new PdfReader(Lbyte.FirstOrDefault()); document.NewPage(); for (int i = 1; i <= reader.NumberOfPages; i++) { //for循环新增文档页数,并copy pdf数据 PdfImportedPage imported = copy.GetImportedPage(reader, i); copy.AddPage(imported); } reader.Close(); copy.Close(); document.Close(); return(memory.ToArray()); }
//2.4 //Form PDF-File with subgroup E and country only _______________________________________________________________ E.1 (E letters 是中葡文template) private void PrintGroupWithCountry_E(string outputPDFFile, string LtrSubGrp, string PtnCNY) { var E_Group_List = GlobalVar.FPL1LTR_List.Where(grp => grp.LTRSUBGRP.Trim() == LtrSubGrp && grp.PTNCNY.Trim() == PtnCNY).ToList(); //has data if (E_Group_List.Count() > 0) { using (var fs = new FileStream(GlobalVar.wPATH() + outputPDFFile, FileMode.Create)) { iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.A4); PdfSmartCopy copy = new PdfSmartCopy(doc, fs); doc.Open(); foreach (var pageInfo in E_Group_List) { FillTextToPDF_E("input_" + outputPDFFile, copy, pageInfo, LtrSubGrp, PtnCNY); //group E only } copy.Close(); doc.Close(); } } }
public override Object Merge(int companyId, object pdfFiles, string blobPath) { string tempUploadPath = HttpContext.Current.Server.MapPath("~/App_data/uploads/" + Path.GetFileName(blobPath)); using (FileStream stream = new FileStream(tempUploadPath, FileMode.Create)) { PdfReader reader = null; Document sourceDocument = new Document(); List <string> lstfiles = pdfFiles as List <string>; util.ContainerName = "company-" + companyId; Cloudblob = util.BlobContainer.GetBlockBlobReference(blobPath); PdfWriter writer = PdfWriter.GetInstance(sourceDocument, stream); PdfSmartCopy copy = new PdfSmartCopy(sourceDocument, stream); sourceDocument.Open(); lstfiles.ForEach(file => { util.ContainerName = "company-" + companyId; string path = util.getBlob(file); CloudBlockBlob _cblob = util.BlobContainer.GetBlockBlobReference(path); var ms = new MemoryStream(); _cblob.DownloadToStream(ms); long fileByteLength = _cblob.Properties.Length; byte[] fileContents = new byte[fileByteLength]; _cblob.DownloadToByteArray(fileContents, 0); reader = new PdfReader(fileContents); copy.AddDocument(reader); reader.Close(); } ); copy.Close(); } var blobURL = this.Upload(blobPath, tempUploadPath, companyId); return((object)blobURL); }
virtual public void XmpEncodingTest() { String fileName = "xmp_utf-8_encoding"; Document document = new Document(); PdfSmartCopy copy = new PdfSmartCopy(document, new FileStream(OUT_FOLDER + fileName, FileMode.Create)); document.Open(); PdfReader reader = new PdfReader(CMP_FOLDER + "pdf_metadata.pdf"); int pageCount = reader.NumberOfPages; for (int currentPage = 1; currentPage <= pageCount; currentPage++) { PdfImportedPage page = copy.GetImportedPage(reader, currentPage); copy.AddPage(page); } PdfAConformanceLevel pdfaLevel = PdfAConformanceLevel.PDF_A_1B; MemoryStream os = new MemoryStream(); PdfAXmpWriter xmp = new PdfAXmpWriter(os, copy.Info, pdfaLevel, copy); xmp.Close(); copy.XmpMetadata = os.ToArray(); string metadataXml = System.Text.Encoding.GetEncoding("UTF-8").GetString(copy.XmpMetadata); XmlDocument doc = new XmlDocument(); doc.LoadXml(metadataXml); //<-- This is where the exception is thrown document.Close(); copy.Close(); reader.Close(); }
public static byte[] zCombinePdfs(List <byte[]> files) { if (files.Count > 1) { MemoryStream msOutput = new MemoryStream(); PdfReader reader = new PdfReader(files[0]); Document doc = new Document(); PdfSmartCopy copy = new PdfSmartCopy(doc, msOutput); doc.Open(); for (int k = 0; k < files.Count; k++) { for (int i = 1; i < reader.NumberOfPages + 1; i++) { copy.AddPage(copy.GetImportedPage(reader, i)); copy.FreeReader(reader); } } reader.Close(); copy.Close(); doc.Close(); return(msOutput.ToArray()); } else if (files.Count == 1) { return(files[0]); } return(null); }
public void MergeAndStampPdf(bool resetStampEachPage, String[] input, String output, String stamp) { PdfReader stampReader = new PdfReader(pdfContent[stamp]); List <PdfReader> readersToClose = new List <PdfReader>(); readersToClose.Add(stampReader); MemoryStream baos = new MemoryStream(); try { Document document = new Document(); PdfCopy writer = new PdfSmartCopy(document, baos); try { document.Open(); int stampPageNum = 1; foreach (string element in input) { // create a reader for the input document PdfReader documentReader = new PdfReader( new RandomAccessFileOrArray( new RandomAccessSourceFactory().CreateSource(pdfContent[element]) ) , null); for (int pageNum = 1; pageNum <= documentReader.NumberOfPages; pageNum++) { // import a page from the main file PdfImportedPage mainPage = writer.GetImportedPage(documentReader, pageNum); // make a stamp from the page and get under content... PdfCopy.PageStamp pageStamp = writer.CreatePageStamp(mainPage); // import a page from a file with the stamp... if (resetStampEachPage) { stampReader = new PdfReader(pdfContent[stamp]); readersToClose.Add(stampReader); } PdfImportedPage stampPage = writer.GetImportedPage(stampReader, stampPageNum++); // add the stamp template, update stamp, and add the page pageStamp.GetOverContent().AddTemplate(stampPage, 0, 0); pageStamp.AlterContents(); writer.AddPage(mainPage); if (stampPageNum > stampReader.NumberOfPages) { stampPageNum = 1; } } } } finally { writer.Close(); document.Close(); } } finally { foreach (PdfReader stampReaderToClose in readersToClose) { stampReaderToClose.Close(); } } pdfContent[output] = baos.ToArray(); }
/// <summary> /// Returns a memory stream for a combined document, comprising all the supplied pdf documents /// </summary> /// <param name="documents">The documents to combine</param> /// <returns>The memory stream for the combined document</returns> public MemoryStream PdfDocumentCombinedStream(IList <Document> documents) { // If we have no documents at all, do not proceed if (documents.Count == 0) { return(null); } // Initialise the new PDF document object to create, the output stream to write its data to, and the PdfSmartCopy writer var combinedDocument = new iTextSharp.text.Document(); var oCombinedDocumentStream = new MemoryStream(); var pdfWriter = new PdfSmartCopy(combinedDocument, oCombinedDocumentStream); // Set compression options pdfWriter.SetPdfVersion(PdfWriter.PDF_VERSION_1_7); pdfWriter.CompressionLevel = PdfStream.BEST_COMPRESSION; pdfWriter.SetFullCompression(); // Open document object to write to - this is the actual object that gets created and modified in memoey // The pdf writer outputs this to the memory stream (if we wanted to, we could just as easily write to a file instead) combinedDocument.Open(); // Iterate through all pdf documents in the collection foreach (var document in documents) { var oStream = new MemoryStream(); // Read individual document content var reader = new PdfReader(document.LatestRevision.Content.Content); // Create a pdf stamper to modify the content and output it to a memory stream // We set it to flatten the form field data in the output, so it cannot be modified // Note that text fields are flattened explicitly later in the method // so the only form fields that actually get flattened are radio buttons, check boxes etc var stamper = new PdfStamper(reader, oStream) { FormFlattening = true }; var form = stamper.AcroFields; var keys = new ArrayList(form.Fields.Keys.ToList()); // Create an arial base font // We use this during flattening of text fields var arialFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF"); var arialBaseFont = BaseFont.CreateFont(arialFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); foreach (var key in keys) { if (form.GetFieldType(key.ToString()) == 4) { // Text field // Render the form field content as a replacement text (Phrase) object // We do this here as the built-in FormFlattening option causes a font error in the final pdf const float fontSize = 8.0f; const float leading = 8.0f; const float minimumHeight = 12.5f; const float adjustmentY = 1.5f; // Get field positioning information var fieldPositions = form.GetFieldPositions(key.ToString()); if (fieldPositions.Count == 0) { break; } var fieldPosition = fieldPositions[0]; var height = fieldPosition.position.Top - fieldPosition.position.Bottom; var width = fieldPosition.position.Right - fieldPosition.position.Left; var heightAdjustment = height < minimumHeight ? minimumHeight - height : 0.0f; // Generate the Phrase object which holds the rendered text, and populate it using the contents of the form field var phrase = new Phrase(leading, form.GetField(key.ToString()), new iTextSharp.text.Font(arialBaseFont, fontSize)); // Table object to hold the Phrase // This allows us to set the vertical and horizontal alignment of each rendered Phrase var table = new PdfPTable(1) { WidthPercentage = 100 }; table.SetWidths(new[] { width }); // Table cell object in which the Phrase will be positioned var cell = new PdfPCell { FixedHeight = height + heightAdjustment, Border = iTextSharp.text.Rectangle.NO_BORDER, VerticalAlignment = Element.ALIGN_MIDDLE, HorizontalAlignment = Element.ALIGN_LEFT }; cell.AddElement(phrase); table.AddCell(cell); // We now create our ColumnText wrapper, which allows us to position the table in the same place as the original form field var columnText = new ColumnText(stamper.GetOverContent(fieldPosition.page)); columnText.SetSimpleColumn(fieldPosition.position.Left, fieldPosition.position.Bottom + adjustmentY - heightAdjustment, fieldPosition.position.Right, fieldPosition.position.Top + adjustmentY); columnText.AddElement(table); columnText.Go(); // Finally, all that is left to do is to remove the original form field form.RemoveField(key.ToString()); } else { // Non-text field // Append each form field name to have a unique suffix // This is so that when we join all the documents together, all the form field names are unique and therefore still rendered correctly form.RenameField(key.ToString(), string.Format("{0}{1}", key, documents.IndexOf(document))); } } // We now compress all images in the pdf // http://cjhaas.com/blog/2012/01/06/how-to-recompress-images-in-a-pdf-using-itextsharp/ const int physicalSizePercentage = 90; const int compressionPercentage = 85; var numberOfPages = reader.NumberOfPages; for (var currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++) { // Get the XObject structure var resources = (PdfDictionary)PdfReader.GetPdfObject(reader.GetPageN(currentPageIndex).Get(PdfName.RESOURCES)); var xObjects = (PdfDictionary)PdfReader.GetPdfObject(resources.Get(PdfName.XOBJECT)); if (xObjects != null) { // Loop through each XObject key foreach (var key in xObjects.Keys) { var xObject = xObjects.Get(key); if (xObject.IsIndirect()) { // Get the current key as a pdf object var imgObject = (PdfDictionary)PdfReader.GetPdfObject(xObject); // Is the object an image? if (imgObject != null && imgObject.Get(PdfName.SUBTYPE).Equals(PdfName.IMAGE)) { // Note: There are several different types of filters we're only handing the simplest one here which is basically raw jpeg if (imgObject.Get(PdfName.FILTER).Equals(PdfName.DCTDECODE)) { // Get the raw bytes of the image var oldBytes = PdfReader.GetStreamBytesRaw((PRStream)imgObject); byte[] newBytes; // Wrap a stream around our original image using (var memoryStream = new MemoryStream(oldBytes)) { // Convert the bytes into a .NET image using (var oldImage = System.Drawing.Image.FromStream(memoryStream)) { // Shrink the source image to a percentage of its original size using (var newImage = ShrinkImage(oldImage, physicalSizePercentage / 100.0f)) { // Convert the image to bytes using jpeg newBytes = ConvertImageToBytes(newImage, compressionPercentage); } } } // Create a new iTextSharp image from our bytes var compressedImage = Image.GetInstance(newBytes); // Kill off the old image PdfReader.KillIndirect(xObject); // Add our image in its place stamper.Writer.AddDirectImageSimple(compressedImage, (PRIndirectReference)xObject); } } } } } } stamper.Writer.CloseStream = false; stamper.Close(); // Read modified document content from the pdf stamper's output stream reader = new PdfReader(oStream.ToArray()); numberOfPages = reader.NumberOfPages; // Add each modified page to our combined document object for (var currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++) { var page = pdfWriter.GetImportedPage(reader, currentPageIndex); pdfWriter.AddPage(page); } } // Close the pdf writer and the combined document object // This will flush the output memory stream, and give us our completed document data pdfWriter.CloseStream = false; pdfWriter.Close(); combinedDocument.Close(); // Move the stream position to the beginning then return it oCombinedDocumentStream.Seek(0, SeekOrigin.Begin); return(oCombinedDocumentStream); }
/// <summary> /// Merges pdf files from a byte list /// </summary> /// <param name="files">list of files to merge</param> /// <returns>memory stream containing combined pdf</returns> public static string MergePdfForms(List <string> file_names, string output) { if (file_names.Count > 1) { List <byte[]> files = new List <byte[]>(); foreach (string file_name in file_names) { var file = File.ReadAllBytes(file_name); files.Add(file); } string[] names; PdfStamper stamper; MemoryStream msTemp = null; PdfReader pdfTemplate = null; PdfReader pdfFile; Document doc; PdfWriter pCopy; MemoryStream msOutput = new MemoryStream(); pdfFile = new PdfReader(files[0]); doc = new Document(); pCopy = new PdfSmartCopy(doc, msOutput); pCopy.PdfVersion = PdfWriter.VERSION_1_7; doc.Open(); for (int k = 0; k < files.Count; k++) { for (int 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 (string 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); } } FileStream f = new FileStream(output, FileMode.Create); msOutput.WriteTo(f); msOutput.Flush(); f.Flush(); pdfFile.Close(); pCopy.Close(); doc.Close(); msOutput.Close(); f.Close(); return(output); } else if (file_names.Count == 1) { File.Copy(file_names.First(), output); return(output); } return(null); }
public void convertoonepdf(String Idproofimage, String resiproofimage, string documentproof, String VC, string PDFName, String Ecafno) { try { var creatfpdf = Server.MapPath("~/MyExcelFile/"); var finalPDF = System.IO.Path.Combine(creatfpdf, PDFName); var Header_text = getheader_text(); //This variable will eventually hold our combined PDF as a byte array Byte[] finalFileBytes; //Write everything to a MemoryStream using (var finalFile = new System.IO.MemoryStream()) { //Create a generic Document Document doc = new Document(); //Use PdfSmartCopy to intelligently merge files PdfSmartCopy copy = new PdfSmartCopy(doc, finalFile); //Open our document for writing doc.Open(); //#1 - Import the SSRS report //Bind a reader to our SSRS report PdfReader.unethicalreading = true; if (Idproofimage != "http://localhost/yesbank/MobImages/") { if (Idproofimage.ToUpper().Contains(".PDF")) { try { PdfReader reader1 = new PdfReader(Idproofimage); for (var i = 1; i <= reader1.NumberOfPages; i++) { copy.AddPage(copy.GetImportedPage(reader1, i)); } reader1.Close(); } catch { } } else { try { iTextSharp.text.Rectangle pageSize = null; WebClient wc = new WebClient(); byte[] bytes = wc.DownloadData(Idproofimage); MemoryStream ms = new MemoryStream(bytes); using (var srcImage = new Bitmap(ms)) { if (srcImage.Width < 580) { pageSize = new iTextSharp.text.Rectangle(0, 0, 580, srcImage.Height + 100); } else { pageSize = new iTextSharp.text.Rectangle(0, 0, srcImage.Width, srcImage.Height + 100); } } //Will eventually hold the PDF with the image as a byte array Byte[] imageBytes; //Simple image to PDF using (var m = new MemoryStream()) { Document d = new Document(pageSize, 0, 0, 0, 0); PdfWriter w = PdfWriter.GetInstance(d, m); d.Open(); d.Add(iTextSharp.text.Image.GetInstance(Idproofimage)); d.Close(); //Grab the bytes before closing out the stream imageBytes = m.ToArray(); } //Now merge using the same merge code as #1 PdfReader reader1 = new PdfReader(imageBytes); for (var i = 1; i <= reader1.NumberOfPages; i++) { copy.AddPage(copy.GetImportedPage(reader1, i)); } reader1.Close(); ms.Close(); } catch { } } } //#3 - Merge additional PDF if (resiproofimage != "http://localhost/yesbank/MobImages/") { if (resiproofimage.ToUpper().Contains(".PDF")) { try { PdfReader reader1 = new PdfReader(resiproofimage); for (var i = 1; i <= reader1.NumberOfPages; i++) { copy.AddPage(copy.GetImportedPage(reader1, i)); } reader1.Close(); } catch { } } else { try { iTextSharp.text.Rectangle pageSize = null; WebClient wc = new WebClient(); byte[] bytes = wc.DownloadData(resiproofimage); MemoryStream ms = new MemoryStream(bytes); using (var srcImage = new Bitmap(ms)) { if (srcImage.Width < 580) { pageSize = new iTextSharp.text.Rectangle(0, 0, 580, srcImage.Height + 100); } else { pageSize = new iTextSharp.text.Rectangle(0, 0, srcImage.Width, srcImage.Height + 100); } } //Will eventually hold the PDF with the image as a byte array Byte[] imageBytes; //Simple image to PDF using (var m = new MemoryStream()) { Document d = new Document(pageSize, 0, 0, 0, 0); PdfWriter w = PdfWriter.GetInstance(d, m); d.Open(); d.Add(iTextSharp.text.Image.GetInstance(resiproofimage)); d.Close(); //Grab the bytes before closing out the stream imageBytes = m.ToArray(); } //Now merge using the same merge code as #1 PdfReader reader1 = new PdfReader(imageBytes); for (var i = 1; i <= reader1.NumberOfPages; i++) { copy.AddPage(copy.GetImportedPage(reader1, i)); } reader1.Close(); ms.Close(); } catch { } } } if (documentproof != "http://localhost/yesbank/MobImages/") { try { PdfReader reader1 = new PdfReader(documentproof); for (var i = 1; i <= reader1.NumberOfPages; i++) { copy.AddPage(copy.GetImportedPage(reader1, i)); } reader1.Close(); } catch (Exception ex) { } } doc.Close(); copy.Close(); //Grab the bytes before closing the stream finalFileBytes = finalFile.ToArray(); System.IO.File.WriteAllBytes(finalPDF, finalFileBytes); byte[] bytesaa = File.ReadAllBytes(finalPDF); iTextSharp.text.Font blackFont = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.NORMAL, BaseColor.RED); using (MemoryStream stream = new MemoryStream()) { PdfReader reader = new PdfReader(bytesaa); using (PdfStamper stamper = new PdfStamper(reader, stream)) { int pages = reader.NumberOfPages; for (int i = 1; i <= pages; i++) { ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_RIGHT, new Phrase("E-CAF No. : " + Ecafno, blackFont), 568f, 15f, 0); } } bytesaa = stream.ToArray(); } File.WriteAllBytes(finalPDF, bytesaa); } } catch { } }