public virtual void TestFullCompression2() { Directory.CreateDirectory("PdfCopyTest/"); String outfile = "PdfCopyTest/out-forms.pdf"; String first = RESOURCES + "subscribe.pdf"; String second = RESOURCES + "filled_form_1.pdf"; FileStream out_ = new FileStream(outfile, FileMode.Create); PdfReader reader = new PdfReader(first); PdfReader reader2 = new PdfReader(second); Document pdfDocument = new Document(); PdfCopy pdfCopy = new PdfCopy(pdfDocument, out_); pdfCopy.SetMergeFields(); pdfCopy.SetFullCompression(); pdfCopy.CompressionLevel = PdfStream.BEST_COMPRESSION; pdfDocument.Open(); pdfCopy.AddDocument(reader); pdfCopy.AddDocument(reader2); pdfCopy.Close(); reader.Close(); reader2.Close(); reader = new PdfReader("PdfCopyTest/out-forms.pdf"); Assert.NotNull(reader.GetPageN(1)); reader.Close(); }
public static void CreateMergedPDF(string targetPDF, string pathcopertina, Dictionary <Guid, string> listaEmendamentiGenerati) { try { using (var stream = new FileStream(targetPDF, FileMode.Create)) { var pdfDoc = new Document(PageSize.A4); var pdf = new PdfCopy(pdfDoc, stream); pdfDoc.Open(); //Aggiungo la copertina pdf.AddDocument(new PdfReader(pathcopertina)); foreach (var item in listaEmendamentiGenerati) { pdf.AddDocument(new PdfReader(item.Value)); } if (pdfDoc != null) { pdfDoc.Close(); } Log.Debug("PDF merge complete."); } } catch (Exception ex) { Log.Error("CreateMergedPDF Error-->", ex); throw ex; } }
public virtual void CopyFields1Test() { Document pdfDocument = new Document(); Directory.CreateDirectory("PdfCopyTest/"); PdfCopy copier = new PdfCopy(pdfDocument, new FileStream("PdfCopyTest/copyFields.pdf", FileMode.Create)); copier.SetMergeFields(); pdfDocument.Open(); PdfReader readerMain = new PdfReader(RESOURCES + "fieldsOn3-sPage.pdf"); PdfReader secondSourceReader = new PdfReader(RESOURCES + "fieldsOn2-sPage.pdf"); PdfReader thirdReader = new PdfReader(RESOURCES + "appearances1.pdf"); copier.AddDocument(readerMain); copier.CopyDocumentFields(secondSourceReader); copier.AddDocument(thirdReader); copier.Close(); readerMain.Close(); secondSourceReader.Close(); thirdReader.Close(); CompareTool compareTool = new CompareTool(); String errorMessage = compareTool.CompareByContent("PdfCopyTest/copyFields.pdf", RESOURCES + "cmp_copyFields.pdf", "PdfCopyTest/", "diff"); if (errorMessage != null) { Assert.Fail(errorMessage); } }
public static void ReplaceCoverPDF(string InFile, string InCover, string OutFile) { if (CoverFunction == 0) { List <string> Files = new List <string> { InFile, InCover }; Files.Sort(); MergePDF(Files, OutFile); return; } LogHelper.Log("Replace the cover to the original file", LogType.Successful); FileStream stream = null; Document doc = null; PdfCopy pdf = null; try { stream = new FileStream(OutFile, FileMode.Create); doc = new Document(); pdf = new PdfCopy(doc, stream); doc.Open(); //Aggiungo la cover iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(InCover); int coverPage = reader.NumberOfPages; LogHelper.Log($"Add the cover: {InCover} of {coverPage} pages"); pdf.AddDocument(reader); reader.Close(); //Aggiungo il resto del documento reader = new iTextSharp.text.pdf.PdfReader(InFile); int count = reader.NumberOfPages; coverPage++; List <int> pages = Enumerable.Range(coverPage, count - coverPage + 1).ToList(); LogHelper.Log($"Add the file: {InFile} from Page: {coverPage}"); pdf.AddDocument(reader, pages); reader.Close(); AddBookmarks(InFile, pdf); } catch (Exception e) { LogHelper.Log(e.ToString(), LogType.Error); } finally { pdf?.Dispose(); doc?.Dispose(); stream?.Dispose(); } }
private void RenderPDF(ArrayList pages) { String coverName = "Onix.ClientCenter.UI.AccountPayable.TaxDocument.Resources.WHT53_041060.pdf"; String detailName = "Onix.ClientCenter.UI.AccountPayable.TaxDocument.Resources.290360_attach53.pdf"; if (taxDocType == TaxDocumentType.TaxDocRev3) { coverName = "Onix.ClientCenter.UI.AccountPayable.TaxDocument.Resources.270360_WHT3.pdf"; detailName = "Onix.ClientCenter.UI.AccountPayable.TaxDocument.Resources.270360_attach3.pdf"; } if (File.Exists(pdfName)) { File.Delete(pdfName); } Assembly assembly = Assembly.GetExecutingAssembly(); FileStream outputStream = new FileStream(pdfName, FileMode.Create); Document pdfDoc = new Document(PageSize.A4); PdfCopy pdf = new PdfCopy(pdfDoc, outputStream); pdfDoc.Open(); Stream coverPageStream = assembly.GetManifestResourceStream(coverName); MemoryStream m = new MemoryStream(); PdfStamper pdfStamper = new PdfStamper(new PdfReader(coverPageStream), m); AcroFields pdfFormFields = pdfStamper.AcroFields; populateCoverFormValue(pdfFormFields, 1); pdfStamper.FormFlattening = true; pdfStamper.Close(); pdf.AddDocument(new PdfReader(new MemoryStream(m.ToArray()))); int max = pages.Count; int i = 0; foreach (CTaxFormPageRv3_53 page in pages) { i++; Stream detailPageStream = assembly.GetManifestResourceStream(detailName); MemoryStream n = new MemoryStream(); PdfStamper pdfDetailStamper = new PdfStamper(new PdfReader(detailPageStream), n); AcroFields pdfDetailFormFields = pdfDetailStamper.AcroFields; populateDetailFormValue(pdfDetailFormFields, 2, i, pages.Count, page); pdfDetailStamper.FormFlattening = true; pdfDetailStamper.Close(); pdf.AddDocument(new PdfReader(new MemoryStream(n.ToArray()))); UpdateProgress(i, max); } pdfDoc.Close(); pdf.Close(); }
public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { using (MemoryStream ms = new MemoryStream()) { using (var document = new Document()) { PdfReader reader1 = new PdfReader(RenameFieldsIn(DATASHEET, 1)); PdfReader reader2 = new PdfReader(RenameFieldsIn(DATASHEET, 2)); using (var copy = new PdfCopy(document, ms)) { copy.SetMergeFields(); document.Open(); copy.AddDocument(reader1); copy.AddDocument(reader2); } reader1.Close(); reader2.Close(); zip.AddEntry(RESULT, ms.ToArray()); } } zip.AddFile(DATASHEET, ""); zip.Save(stream); } }
private void RenderPDF(ArrayList pages) { String coverName = "Onix.ClientCenter.UI.AccountPayable.TaxDocument.Resources.PP1_SUMMARY.pdf"; String detailName = "Onix.ClientCenter.UI.AccountPayable.TaxDocument.Resources.PP1_DETAIL.pdf"; if (File.Exists(pdfName)) { File.Delete(pdfName); } Assembly assembly = Assembly.GetExecutingAssembly(); FileStream outputStream = new FileStream(pdfName, FileMode.Create); Document pdfDoc = new Document(PageSize.A4); PdfCopy pdf = new PdfCopy(pdfDoc, outputStream); pdfDoc.Open(); Stream coverPageStream = assembly.GetManifestResourceStream(coverName); MemoryStream m = new MemoryStream(); PdfStamper pdfStamper = new PdfStamper(new PdfReader(coverPageStream), m); AcroFields pdfFormFields = pdfStamper.AcroFields; populateCoverFormValue(pdfFormFields, 1); pdfStamper.FormFlattening = true; pdfStamper.Close(); pdf.AddDocument(new PdfReader(new MemoryStream(m.ToArray()))); int max = pages.Count; int i = 0; foreach (CTaxFormPageRv1 page in pages) { i++; Stream detailPageStream = assembly.GetManifestResourceStream(detailName); MemoryStream n = new MemoryStream(); PdfStamper pdfDetailStamper = new PdfStamper(new PdfReader(detailPageStream), n); AcroFields pdfDetailFormFields = pdfDetailStamper.AcroFields; populateDetailFormValue(pdfDetailFormFields, 2, i, pages.Count, page); pdfDetailStamper.FormFlattening = true; pdfDetailStamper.Close(); PdfReader reader = new PdfReader(new MemoryStream(n.ToArray())); PdfDictionary pd = reader.GetPageN(1); pd.Put(PdfName.ROTATE, new PdfNumber(90)); pdf.AddDocument(reader); UpdateProgress(i, max); } pdfDoc.Close(); pdf.Close(); }
public static void FlatPDFonlyFistPage(List <string> files) { LogHelper.Log("Flatt all PDF comments", LogType.Successful); foreach (var file in files) { string OutFile = $"{Path.GetDirectoryName(file)}{Path.DirectorySeparatorChar}{Path.GetFileNameWithoutExtension(file)}_flat.pdf"; LogHelper.Log($"Flattening file: { Path.GetFileNameWithoutExtension(file)}"); using (FileStream stream = new FileStream(OutFile, FileMode.Create)) { PdfReader reader = null; PdfStamper stamper = null; try { var memStream1 = new MemoryStream(); reader = new PdfReader(file); reader.SelectPages("1"); stamper = new PdfStamper(reader, memStream1) { FormFlattening = true, AnnotationFlattening = true, FreeTextFlattening = true, }; stamper.Close(); PdfReader readerfirstPage = new PdfReader(memStream1.ToArray()); Document doc = new Document(); PdfCopy pdf = new PdfCopy(doc, stream); doc.Open(); pdf.AddDocument(readerfirstPage); PdfReader readerOtherPages = new PdfReader(file); if (readerOtherPages.NumberOfPages > 2) { readerOtherPages.SelectPages($"2-{readerOtherPages.NumberOfPages}"); pdf.AddDocument(readerOtherPages); } doc.Close(); pdf.Close(); } catch (Exception e) { LogHelper.Log(e.ToString(), LogType.Error); reader?.Close(); } finally { reader?.Close(); } } } }
/// <summary> /// /// </summary> /// <param name="fileOne"></param> /// <param name="fileTwo"></param> /// <param name="newFile"></param> public static void ConcatPdf(string fileOne, string fileTwo, string newFile) { //si le premier fichier en entrée est aussi le fichier de sortie on concatène ce dernier var append = fileOne.Equals(newFile); if (append) { //on construit le fichier sortie dans un autre emplacement string cardFolder = Path.Combine(ServiceCfg.OutputFolderPath, @"pages\"); newFile = Path.Combine(cardFolder, Path.GetFileName(newFile)); } //fusion des pdf using (FileStream stream = new FileStream(newFile, FileMode.Create)) { Document pdfDoc = new Document(); PdfReader reader; PdfCopy pdf = new PdfCopy(pdfDoc, stream); pdfDoc.Open(); if (File.Exists(fileOne)) { reader = new PdfReader(fileOne); pdf.AddDocument(reader); reader.Close(); } if (File.Exists(fileTwo)) { reader = new PdfReader(fileTwo); pdf.AddDocument(reader); reader.Close(); } if (pdfDoc != null) { pdf.Close(); pdfDoc.Close(); if (append) { if (File.Exists(fileOne)) { File.Delete(fileOne); } //on déplace le fichier sortie obtenu à l'emplacement d'origine File.Move(newFile, fileOne); } } } }
public static void combinePDF(string outputFile, List <listboxPdfObjects> files) { if (files.Count > 0) { using (var fileStream = new FileStream(outputFile, FileMode.OpenOrCreate)) { Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35); var pdfCopy = new PdfCopy(doc, fileStream); doc.Open(); foreach (var pdf in files) { try { var pdfReader = new PdfReader(pdf.fullname); pdfCopy.AddDocument(pdfReader); pdfReader.Dispose(); } catch (Exception e) { } } pdfCopy.Dispose(); doc.Dispose(); } } }
private static void Merge <TSource>(Stream target, Func <TSource, PdfReader> createPdfReader, params TSource[] sources) { if (sources.Length == 0) { throw new ArgumentException("At least one source must be given."); } Document document = null; PdfReader reader = null; try { document = new Document(); PdfCopy pdf = new PdfCopy(document, target); document.Open(); foreach (TSource file in sources) { reader = createPdfReader(file); pdf.AddDocument(reader); reader.Close(); } } catch (Exception e) { reader?.Close(); throw new PdfMergeFailedException("Failed to merge pdfs", e); } finally { document?.Close(); } }
public HttpResponseMessage Merge(string urls) { var urlArray = urls.Split(','); var wc = new WebClient(); var pdfContents = urlArray.Select(u => Download(wc, u)).ToList(); byte[] mergedPdf = null; using (var ms = new MemoryStream()) { using (var document = new Document()) { using (var copy = new PdfCopy(document, ms)) { document.Open(); pdfContents.ForEach(c => { if (c != null) { copy.AddDocument(new PdfReader(c)); } }); } } mergedPdf = ms.ToArray(); } var response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new ByteArrayContent(mergedPdf); response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); return(response); }
/// <summary> /// Add PdfFile /// </summary> /// <param name="fullpath"></param> public void Add(string fullpath, List <Dictionary <String, Object> > parentBookmarks) { var pdfFilename = Path.GetFileName(fullpath); PdfReader reader = null; try { // Open PDF reader = new PdfReader(fullpath); // Although this method seems to have a large memory consumption, it is troublesome as this is done copy.AddDocument(reader); AddBookmark(reader, pdfFilename, parentBookmarks); // Update count of pages pageCount += reader.NumberOfPages; } catch (Exception e) { logger?.LogError(e, $"Failed to join {pdfFilename}"); throw; } finally { reader?.Close(); } }
/// <summary> /// Слияние нескольких pdf файлов в один /// </summary> /// <param name="fileNames">Массив файлов для слияния</param> /// <param name="outFile">Файл в который вывести результат</param> public static void Combine(string[] fileNames, string outFile) { using (FileStream stream = new FileStream(outFile, FileMode.Create)) { Document document = new Document(); PdfCopy pdf = new PdfCopy(document, stream); PdfReader reader = null; try { document.Open(); foreach (string file in fileNames) { reader = new PdfReader(file); pdf.AddDocument(reader); reader.Close(); } } finally { if (document != null) { document.Close(); } } } }
public static void MergePDF(List <string> files, string OutFile) { LogHelper.Log("Join all files into a single PDF", LogType.Successful); FileStream stream = null; Document doc = null; PdfCopy pdf = null; try { stream = new FileStream(OutFile, FileMode.Create); doc = new Document(); pdf = new PdfCopy(doc, stream); doc.Open(); foreach (string file in files) { LogHelper.Log($"Add the file: {file}"); pdf.AddDocument(new iTextSharp.text.pdf.PdfReader(file)); } AddBookmarks(files, pdf); } catch (Exception e) { LogHelper.Log(e.ToString(), LogType.Error); } finally { pdf?.Dispose(); doc?.Dispose(); stream?.Dispose(); } }
/// <summary> /// Merges all files provided as a list of byte arrays. /// </summary> /// <param name="mutiplePdfFileBytes">List of pdf filea as byte arrays.</param> /// <returns>Merged pdf file as byte array.</returns> private static byte[] MergeAllPdfFileBytes(IEnumerable <byte[]> mutiplePdfFileBytes) { using (var ms = new MemoryStream()) { using (var document = new Document()) { using (var mergedPdf = new PdfCopy(document, ms)) { document.Open(); foreach (byte[] pdfFileBytes in mutiplePdfFileBytes) { if (pdfFileBytes != null && pdfFileBytes.Length > 0) { using (var pdfReader = new PdfReader(pdfFileBytes)) { mergedPdf.AddDocument(pdfReader); } } } } } return(ms.ToArray()); } }
/// <summary> /// See http://weblogs.sqlteam.com/mladenp/archive/2014/01/10/simple-merging-of-pdf-documents-with-itextsharp-5-4-5.aspx /// </summary> /// <param name="sourceDir"></param> /// <param name="destPdf"></param> public static void MergeAll(string sourceDir, string destPdf) { using (FileStream stream = new FileStream(destPdf, FileMode.Create)) { Document pdfDoc = new Document(); PdfCopy pdf = new PdfCopy(pdfDoc, stream); Regex numpattern = new Regex(@"\d+(?=\.pdf)"); pdfDoc.Open(); List <string> files = Directory.GetFiles(sourceDir).ToList(); files.Sort((a, b) => int.Parse(numpattern.Match(a).Value).CompareTo(int.Parse(numpattern.Match(b).Value))); Console.WriteLine("Merging files count: " + files.Count); int i = 1; foreach (string file in files) { Console.WriteLine(i + ". Adding: " + file); pdf.AddDocument(new PdfReader(file)); i++; } if (pdfDoc != null) { pdfDoc.Close(); } Console.WriteLine("SpeedPASS PDF merge complete."); } }
static void CreateMergedPDF(string targetPDF, string sourceDir) { using (FileStream stream = new FileStream(targetPDF, FileMode.Create)) { Document pdfDoc = new Document(PageSize.A4); PdfCopy pdf = new PdfCopy(pdfDoc, stream); pdfDoc.Open(); var files = Directory.GetFiles(sourceDir); Console.WriteLine("Merging files count: " + files.Length); int i = 1; foreach (string file in files) { Console.WriteLine(i + ". Adding: " + file); pdf.AddDocument(new PdfReader(file)); i++; } if (pdfDoc != null) { pdfDoc.Close(); } Console.WriteLine("PDF merge complete."); } }
public string MergePDF(List <string> sourceFileList, string outputFilePath) { //we need iTextSharp code here for merge pdfs's, please import its library from iTextSharp //stream object to hold merge pdfs from below processing logic using (var fileStream = new FileStream(outputFilePath, FileMode.Create)) { //we need a pdf document object that can hold all merged pdf contents using (var pdfDocument = new Document()) { //mapping stream to pdfDocument object var pdf = new PdfCopy(pdfDocument, fileStream); //Open the PDF for Merge pdfDocument.Open(); //loping through all files from list collection foreach (string file in sourceFileList) { pdf.AddDocument(new PdfReader(file)); } } } return(outputFilePath); }
public static void AppendPdfDocument(this PdfCopy pdfCopy, byte[] pdfBytes) { using (var pdfReader = new PdfReader(pdfBytes)) { pdfCopy.AddDocument(pdfReader); } }
public virtual void TestNeedAppearancesMixed() { String f1 = RESOURCES + "appearances1.pdf"; String f2 = RESOURCES + "appearances2(needAppearancesFalse).pdf"; String f3 = RESOURCES + "appearances3(needAppearancesFalseWithStreams).pdf"; String f4 = RESOURCES + "appearances4.pdf"; Directory.CreateDirectory("PdfCopyTest/"); FileStream outputPdfStream = new FileStream("PdfCopyTest/appearances(mixed).pdf", FileMode.Create); Document document = new Document(); PdfCopy copy = new PdfCopy(document, outputPdfStream); copy.SetMergeFields(); document.Open(); foreach (String f in new String[] { f1, f2, f3, f4 }) { PdfReader r = new PdfReader(f); copy.AddDocument(r); } copy.Close(); CompareTool compareTool = new CompareTool(); String errorMessage = compareTool.CompareByContent("PdfCopyTest/appearances(mixed).pdf", RESOURCES + "cmp_appearances(mixed).pdf", "PdfCopyTest/", "diff"); if (errorMessage != null) { Assert.Fail(errorMessage); } }
public static bool MergePDFs(IEnumerable <string> fileNames, string targetPdf) { bool merged = true; using (FileStream stream = new FileStream(targetPdf, FileMode.Create)) { Document document = new Document(); PdfCopy pdf = new PdfCopy(document, stream); PdfReader reader = null; try { document.Open(); foreach (string file in fileNames) { reader = new PdfReader(file); pdf.AddDocument(reader); reader.Close(); } } catch (Exception) { merged = false; if (reader != null) { reader.Close(); } } finally { document.Close(); } } return(merged); }
public static void CompinePDFFiles(bool ImagePDFDocumentCreated, string FullPath, string FullPath_ImagePDF, HttpPostedFileBase[] Images, Random Rnd_FileNames, string Dirpath, List <string> AllCurrentFiles) { using (FileStream stream_FinalFile = new FileStream(FullPath, FileMode.OpenOrCreate)) { Document pdfDoc = new Document(); PdfCopy pdf = new PdfCopy(pdfDoc, stream_FinalFile); pdfDoc.Open(); if (ImagePDFDocumentCreated) { pdf.AddDocument(new PdfReader(FullPath_ImagePDF)); } foreach (var im in Images) { Constants.Enumerations.UploadFileTypesEnum FileType = GetFileType(im); switch (FileType) { case Constants.Enumerations.UploadFileTypesEnum.Pdf: pdf.AddDocument(new PdfReader(im.InputStream)); break; //case Constants.Enumerations.UploadFileTypesEnum.Word: // string RandomFName = GetRandomFileName(Rnd_FileNames); // string CurrentWordRandomFileName = RandomFName + Path.GetExtension(im.FileName); // string NewPdfRandomFileName = RandomFName + ".pdf"; // string CurrentWordFullPath = Dirpath + @"\" + CurrentWordRandomFileName; // string NewPdfFullPath = Dirpath + @"\" + NewPdfRandomFileName; // CovertWordToPDF(im, CurrentWordFullPath, NewPdfFullPath); // AllCurrentFiles.Add(CurrentWordRandomFileName); // AllCurrentFiles.Add(NewPdfRandomFileName); // pdf.AddDocument(new PdfReader(NewPdfFullPath)); // break; default: break; } } pdfDoc.Close(); } }
public ActionResult GoToViewHoSo(long hoSoId = 0, bool exportExcel = false) { var hoSo = _hoSoRepos.Get(hoSoId); if (hoSo != null) { if (hoSo.IsCA == true) { var stream = new MemoryStream(); var outStream = new MemoryStream(); byte[] byteInfo = stream.ToArray(); using (iTextSharp.text.Document document = new iTextSharp.text.Document()) using (PdfCopy copy = new PdfCopy(document, outStream)) { document.Open(); string ATTP_FILE_PDF = GetUrlFileDefaut(); string filePath = Path.Combine(ATTP_FILE_PDF, hoSo.DuongDanTepCA); var fileBytes = System.IO.File.ReadAllBytes(filePath); copy.AddDocument(new PdfReader(fileBytes)); } return(File(outStream.ToArray(), "application/pdf")); } else { //File Template var xls = FileHoSo(hoSoId); byte[] fileTemplate = null; using (FlexCel.Render.FlexCelPdfExport pdf = new FlexCel.Render.FlexCelPdfExport()) { pdf.Workbook = xls; using (MemoryStream ms = new MemoryStream()) { pdf.BeginExport(ms); pdf.ExportAllVisibleSheets(false, "PDF"); pdf.EndExport(); ms.Position = 0; fileTemplate = ms.ToArray(); } } //Copy List File Đính Kèm string ATTP_FILE_PDF = GetUrlFileDefaut(); var outStream = new MemoryStream(); using (iTextSharp.text.Document document = new iTextSharp.text.Document()) using (PdfCopy copy = new PdfCopy(document, outStream)) { document.Open(); copy.AddDocument(new PdfReader((fileTemplate))); } return(File(outStream.ToArray(), "application/pdf")); } } else { return(null); } }
public static void CreateSinglePDF(List <byte[]> pages, string pdfFilePath) { // If only a single PDF is provided, check for early exit. if ((pages.Count == 1) && IsPDF(pages[0])) { File.WriteAllBytes(pdfFilePath, pages[0]); return; } // Create the document. Document doc = new Document(PageSize.A4, 10f, 10f, 100f, 0f); PdfCopy writer = new PdfCopy(doc, new FileStream(pdfFilePath, FileMode.Create)); doc.Open(); foreach (byte[] page in pages) { if (page != null) { // New page. doc.NewPage(); // If the page is a PDF, simply add the PDF document. if (IsPDF(page)) { writer.AddDocument(new PdfReader(page)); } // Else, let's try to convert it to an image. else { try { writer.AddDocument(new PdfReader(ImageToPDF(page))); } catch { throw new Exception("File contents must comprise either a PDF or image file."); } } } } // Close. doc.Close(); }
public bool CreatePDF(string fName, string[] nFiles) { bool result; using (FileStream stream = new FileStream(fName, FileMode.Create)) { Document newPDF = new Document(); PdfCopy pdf = new PdfCopy(newPDF, stream); PdfReader reader = null; int pages = 0; myOwner.progressBar.Minimum = 0; myOwner.progressBar.Maximum = nFiles.Length; myOwner.progressBar.Visible = true; myOwner.progressBar.Value = 0; try { newPDF.Open(); foreach (string f in nFiles) { if (f != null) { reader = new PdfReader(f); pdf.AddDocument(reader); reader.Close(); if (myOwner.progressBar.Value < myOwner.progressBar.Maximum) { myOwner.progressBar.Value = myOwner.progressBar.Value + 1; } pages++; } } result = true; } catch (Exception) { if (reader != null) { reader.Close(); } result = false; } finally { if (newPDF != null && pages != 0) { newPDF.Close(); } } } myOwner.progressBar.Visible = false; return(result); }
public HttpResponseMessage GetMultiple() { var rs = new LocalReporting().UseBinary(JsReportBinary.GetBinary()).AsUtility().Create(); List <string> mensajes = new List <string> { "1", "2", "3" }; List <Stream> streamPdfs = new List <Stream>(); foreach (var m in mensajes) { var report = rs.RenderAsync(new RenderRequest() { Template = new Template() { Recipe = Recipe.PhantomPdf, Engine = Engine.Handlebars, Content = "Hello from pdf, {{message}}", Phantom = new Phantom { Header = "B&A Systems SAS", Footer = "<div style='text-align:center'>Page number {#pageNum}/{#numPages}</div>", } }, Data = new { message = $"B&A Migrando a jsreport for .NET!!! {m}" } }).Result; streamPdfs.Add(report.Content); } byte[] result = null; using (MemoryStream ms = new MemoryStream()) { Document pdfDoc = new Document(PageSize.A4); PdfCopy pdfUnido = new PdfCopy(pdfDoc, ms); pdfDoc.Open(); streamPdfs.ForEach(item => { var itemPdf = new PdfReader(item); pdfUnido.AddDocument(itemPdf); }); pdfDoc.Close(); result = ms.ToArray(); result = ms.ToArray(); } string nombre = "Test Multiple"; HttpResponseMessage response = DescargarPdf(result, nombre); return(response); }
/// <summary> /// merge some pdf files into one /// </summary> /// <param name="filenames"></param> /// <returns></returns> private string MergeFiles(List <string> filenames) { if (filenames == null) { return(null); } if (filenames.Count.Equals(0)) { return(null); } bool merged = true; var temp = tfh.get("pdf"); using (FileStream fs = new FileStream(temp, FileMode.Create)) { Document d = new Document(); PdfCopy c = new PdfCopy(d, fs); PdfReader r = null; try { d.Open(); foreach (string f in filenames) { r = new PdfReader(f); c.AddDocument(r); r.Close(); } } catch { merged = false; if (r != null) { r.Close(); } } finally { if (d != null) { d.Close(); } } if (merged) { return(temp); } return(null); } }
public virtual void LargeFilePerformanceTest() { const string target = "PdfCopyTest/"; const string output = "copyLargeFile.pdf"; const string cmp = "cmp_copyLargeFile.pdf"; Directory.CreateDirectory(target); Stopwatch timer = new Stopwatch(); timer.Start(); PdfReader firstSourceReader = new PdfReader(RESOURCES + "frontpage.pdf"); PdfReader secondSourceReader = new PdfReader(RESOURCES + "large_pdf.pdf"); Document document = new Document(); PdfCopy copy = new PdfCopy(document, File.Create(target + output)); copy.SetMergeFields(); document.Open(); copy.AddDocument(firstSourceReader); copy.AddDocument(secondSourceReader); copy.Close(); document.Close(); timer.Stop(); Console.WriteLine(timer.ElapsedMilliseconds); CompareTool cmpTool = new CompareTool(); String errorMessage = cmpTool.CompareByContent(target + output, RESOURCES + cmp, target, "diff"); if (errorMessage != null) { Assert.Fail(errorMessage); } }
public virtual void CopyFields4Test() { string target = "PdfCopyTest/"; Directory.CreateDirectory(target); const string outfile = "copyFields4.pdf"; const string inputFile = "link.pdf"; Document document = new Document(); MemoryStream stream = new MemoryStream(); PdfWriter.GetInstance(document, stream); Font font = new Font(BaseFont.CreateFont(RESOURCES + "fonts/georgia.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 9); document.Open(); document.Add(new Phrase("text", font)); document.Close(); Document pdfDocument = new Document(); PdfCopy copier = new PdfCopy(pdfDocument, new FileStream(target + outfile, FileMode.Create)); copier.SetMergeFields(); pdfDocument.Open(); PdfReader reader1 = new PdfReader(RESOURCES + inputFile); PdfReader reader2 = new PdfReader(stream.ToArray()); copier.AddDocument(reader1); copier.AddDocument(reader2); copier.Close(); CompareTool cmpTool = new CompareTool(); string errorMessage = cmpTool.CompareByContent(target + outfile, RESOURCES + "cmp_" + outfile, target, "diff"); if (errorMessage != null) { Assert.Fail(errorMessage); } }