public static void ConcatenatePdfs(List<string> inputPdfFilepaths, Stream outputStream) { Document document = null; PdfCopy writer = null; int fileIndex = 0; foreach (string inputFile in inputPdfFilepaths) { PdfReader reader = new PdfReader(inputFile); reader.ConsolidateNamedDestinations(); int pageCount = reader.NumberOfPages; if (fileIndex == 0) { document = new Document(reader.GetPageSizeWithRotation(1)); writer = new PdfCopy(document, outputStream); document.Open(); } PdfImportedPage page; for (int p = 0; p < pageCount; p++) { ++p; page = writer.GetImportedPage(reader, p); writer.AddPage(page); } PRAcroForm form = reader.AcroForm; if (form != null) { writer.CopyAcroForm(reader); } fileIndex++; } document.Close(); }
public static bool CombineMultiplePDFs(string[] fileNames, string TargetFile) { try { string outFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SamplePDFFolder"); if (!Directory.Exists(outFile)) { Directory.CreateDirectory(outFile); } outFile = Path.Combine(outFile, "MergedPdf.pdf"); // step 1: creation of a document-object Document document = new Document(); // step 2: we create a writer that listens to the document PdfCopy writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create)); if (writer == null) { return(false); } // step 3: we open the document document.Open(); foreach (string fileName in fileNames) { // we create a reader for a certain document PdfReader reader = new PdfReader(fileName); reader.ConsolidateNamedDestinations(); // step 4: we add content for (int i = 1; i <= reader.NumberOfPages; i++) { PdfImportedPage page = writer.GetImportedPage(reader, i); writer.AddPage(page); } PRAcroForm form = reader.AcroForm; if (form != null) { writer.CopyAcroForm(reader); } reader.Close(); } // step 5: we close the document and writer writer.Close(); document.Close(); File.Copy(outFile, TargetFile, true); File.Delete(outFile); return(true); } catch (Exception ex) { Log.This(ex); return(false); } }
static protected void mergePDFFiles(string destinationFile, string[] sourceFiles) { // source: http://stackoverflow.com/questions/6196124/merge-pdf-files int f = 0; String outFile = destinationFile; Document document = null; PdfCopy writer = null; string filePath = null; while (f < sourceFiles.Length) { // build pdf path filePath = sourceFiles[f]; // Create a reader for a certain document if (File.Exists(filePath)) { PdfReader reader = new PdfReader(filePath); // Retrieve the total number of pages int n = reader.NumberOfPages; if (f == 0) { // Step 1: Creation of a document-object document = new Document(reader.GetPageSizeWithRotation(1)); // Step 2: Create a writer that listens to the document writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create)); // Step 3: Open the document document.Open(); } // Step 4: Add content PdfImportedPage page; for (int i = 0; i < n;) { ++i; page = writer.GetImportedPage(reader, i); writer.AddPage(page); } PRAcroForm form = reader.AcroForm; if (form != null) { writer.CopyAcroForm(reader); } } ++f; } // Step 5: Close the document document.Close(); // dispose document.Dispose(); document = null; }
/// <summary> /// Unisce gli stream pdf contenuti nella lista passata in un unico stream pdf /// </summary> /// <param name="files">lista stream pdf</param> /// <returns></returns> public static byte[] MergePDFs(System.Collections.Generic.List <byte[]> files) { MemoryStream ms = null; byte[] result = null; ArrayList master = null; ms = new MemoryStream(); master = new ArrayList(); int f = 0; Document document = null; PdfCopy writer = null; while (f < files.Count) { PdfReader reader = new PdfReader(files[f]); reader.ConsolidateNamedDestinations(); int n = reader.NumberOfPages; if (f == 0) { document = new Document(reader.GetPageSizeWithRotation(1)); writer = new PdfCopy(document, ms); document.Open(); } for (int i = 0; i < n;) { ++i; if (writer != null) { PdfImportedPage page = writer.GetImportedPage(reader, i); writer.AddPage(page); } } PRAcroForm form = reader.AcroForm; if (form != null && writer != null) { writer.CopyAcroForm(reader); } f++; } if (document != null) { document.Close(); } result = ms.ToArray(); ms.Close(); return(result); }
public void MergeFiles() { if (FileList == null || FileList.Count == 0) { MessageBox.Show("No PDF files found on folder."); } else { OutputFileName = System.IO.Path.Combine(Path, $"{OutputFileName}.pdf"); Document document = new Document(); using (FileStream newFileStream = new FileStream(OutputFileName, FileMode.Create)) { PdfCopy writer = new PdfCopy(document, newFileStream); if (writer == null) { return; } document.Open(); foreach (var file in FileList) { PdfReader reader = new PdfReader(file.FullPath); reader.ConsolidateNamedDestinations(); for (int i = 1; i <= reader.NumberOfPages; i++) { PdfImportedPage page = writer.GetImportedPage(reader, i); writer.AddPage(page); } PRAcroForm form = reader.AcroForm; if (form != null) { writer.CopyAcroForm(reader); } reader.Close(); } writer.Close(); document.Close(); } } }
private void CombineMultiplePDFsCer(string[] fileNames, string outFile, bool deleteSource) { // step 1: creation of a document-object Document document = new Document(); //create newFileStream object which will be disposed at the end using (FileStream newFileStream = new FileStream(outFile, FileMode.Create)) { // step 2: we create a writer that listens to the document PdfCopy writer = new iTextSharp.text.pdf.PdfCopy(document, newFileStream); if (writer == null) { return; } // step 3: we open the document document.Open(); foreach (string fileName in fileNames) { // we create a reader for a certain document PdfReader reader = new PdfReader(fileName); reader.ConsolidateNamedDestinations(); // step 4: we add content for (int i = 1; i <= reader.NumberOfPages; i++) { PdfImportedPage page = writer.GetImportedPage(reader, i); writer.AddPage(page); } PRAcroForm form = reader.AcroForm; if (form != null) { writer.CopyAcroForm(reader); } reader.Close(); if (deleteSource) { File.Delete(fileName); } } // step 5: we close the document and writer writer.Close(); document.Close(); }//disposes the newFileStream object }
public static void CombineMultiplePDFs(string[] fileNames, string outFile) { // step 1: creation of a document-object Document document = new Document(); // step 2: we create a writer that listens to the document PdfCopy writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create)); if (writer == null) { return; } // step 3: we open the document document.Open(); foreach (string fileName in fileNames) { // we create a reader for a certain document PdfReader reader = new PdfReader(fileName); reader.ConsolidateNamedDestinations(); // step 4: we add content for (int i = 1; i <= reader.NumberOfPages; i++) { PdfImportedPage page = writer.GetImportedPage(reader, i); writer.AddPage(page); } PRAcroForm form = reader.AcroForm; if (form != null) { writer.CopyDocumentFields(reader); } reader.Close(); } // step 5: we close the document and writer writer.Close(); document.Close(); }
private Byte[] CombineMultiplePDFs(List <Byte[]> fileNames) { Byte[] _Byte = null; Document document = new Document(); MemoryStream _PageAll = new MemoryStream(); PdfCopy writer = new iTextSharp.text.pdf.PdfCopy(document, _PageAll); if (writer == null) { return(_Byte); } // step 3: we open the document document.Open(); foreach (Byte[] fileName in fileNames.ToArray()) { // we create a reader for a certain document PdfReader reader = new PdfReader(fileName); reader.ConsolidateNamedDestinations(); // step 4: we add content for (int i = 1; i <= reader.NumberOfPages; i++) { PdfImportedPage page = writer.GetImportedPage(reader, i); writer.AddPage(page); } PRAcroForm form = reader.AcroForm; if (form != null) { writer.CopyAcroForm(reader); } reader.Close(); } // step 5: we close the document and writer writer.Close(); document.Close(); return(_PageAll.ToArray()); }
public static void CombinePdfs(string[] filenames, string outFile) { Document document = new Document(); PdfCopy writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create)); if (writer == null) { return; } document.Open(); foreach (string filename in filenames) { PdfReader reader = new PdfReader(filename); reader.ConsolidateNamedDestinations(); for (int i = 1; i <= reader.NumberOfPages; i++) { PdfImportedPage page = writer.GetImportedPage(reader, i); writer.AddPage(page); } PRAcroForm form = reader.AcroForm; if (form != null) { writer.CopyAcroForm(reader); } reader.Close(); } writer.Close(); document.Close(); }
public string getFileToPrint(HashSet <string> otid, string newPath) { //string[] directory = Directory.GetDirectories(Globale_Varriables.VAR.pathFileUpload + @"\File\"); string _fullpath = Globale_Varriables.VAR.urlFileUpload + @"\File\"; for (int i = 0; i < otid.Count; i++) { Document doc = new Document(); string _otid = otid.ElementAt(i); string _file = newPath.Replace("{0}", _otid); List <byte[]> _filesByte = new List <byte[]>(); bool _print = false; try { PdfCopy writer = new PdfCopy(doc, new FileStream(_file, FileMode.Create)); /* * PdfWriter pdfW = PdfWriter.GetInstance(doc, new FileStream(_file, FileMode.Create)); * * doc.Close(); */ doc.Open(); //for (int j = 0; j < directory.Length; j++) //{ //if (Globale_Varriables.VAR.pathFileUpload + @"\File\" + otid.ElementAt(i) == directory[j]) //{ string path = _fullpath + _otid; //directory[j]; IEnumerable <string> dirList = System.IO.Directory.EnumerateDirectories(path); foreach (string dir in dirList) { string dpath = dir; string[] type = dpath.Split('\\'); IEnumerable <string> fileList = System.IO.Directory.EnumerateFiles(dpath); DataTable dt = Configs._query.executeProc("dev_getList", "parent@string@DocType#name@string@" + type[type.Length - 1]); int nbr = 0; if (Tools.verifyDataTable(dt)) { nbr = Int32.Parse(dt.Rows[0]["filter"].ToString()); } for (int cp = 1; cp <= nbr; cp++) { string[] files = Directory.GetFiles(dpath, "*.pdf"); foreach (string file in files) { // file , otid.ElementAt(i) PdfReader reader = new PdfReader(file); reader.ConsolidateNamedDestinations(); for (int ic = 1; ic <= reader.NumberOfPages; ic++) { PdfImportedPage page = writer.GetImportedPage(reader, ic); writer.AddPage(page); } PRAcroForm form = reader.AcroForm; if (form != null) { writer.CopyAcroForm(reader); } reader.Close(); /* * byte[] bt = WriteToPdf(new FileInfo(file), otid.ElementAt(i)); * _filesByte.Add(bt); * */ _print = true; } } } string[] _files = Directory.GetFiles(path, "*.pdf"); //directory[j], "*.pdf"); foreach (string file in _files) { PdfReader reader = new PdfReader(file); reader.ConsolidateNamedDestinations(); for (int ic = 1; ic <= reader.NumberOfPages; ic++) { PdfImportedPage page = writer.GetImportedPage(reader, ic); writer.AddPage(page); } PRAcroForm form = reader.AcroForm; if (form != null) { writer.CopyAcroForm(reader); } reader.Close(); /* * //file , otid.ElementAt(i) * byte[] bt = WriteToPdf(new FileInfo(file), otid.ElementAt(i)); * * _filesByte.Add(bt); * */ _print = true; } //} //} writer.Close(); doc.Close(); if (_print) // _filesByte.Count > 0) { /* * _filesByte.Insert(0, File.ReadAllBytes(_file)); * File.WriteAllBytes(_file, PDF.PdfMerger.MergeFiles(_filesByte)); */ Print(_file); } else { File.Delete(_file); } } catch (Exception exx) { } } return(""); }
private void GetFormFields(Stream source) { PdfReader reader = null; try { reader = new PdfReader(source); PRAcroForm form = reader.AcroForm; if (form == null) { //ac.debugText("This document has no fields."); return; } //PdfLister list = new PdfLister(System.out); Hashtable refToField = new Hashtable(); ArrayList fields = form.Fields; foreach (PRAcroForm.FieldInformation field in fields) { refToField.Add(field.Ref.Number, field); } for (int page = 1; page <= reader.NumberOfPages; page++) { PdfDictionary dPage = reader.GetPageN(page); PdfArray annots = (PdfArray)PdfReader.GetPdfObject((PdfObject)dPage.Get(PdfName.ANNOTS)); if (annots == null) { break; } ArrayList ali = annots.ArrayList; PRIndirectReference iRef = null; foreach (PdfObject refObj in ali) { PdfDictionary an = (PdfDictionary)PdfReader.GetPdfObject(refObj); PdfName name = (PdfName)an.Get(PdfName.SUBTYPE); if (name == null || !name.Equals(PdfName.WIDGET)) { break; } PdfArray rect = (PdfArray)PdfReader.GetPdfObject(an.Get(PdfName.RECT)); string fName = ""; PRAcroForm.FieldInformation field = null; while ((an != null)) { PdfString tName = (PdfString)an.Get(PdfName.T); if ((tName != null)) { fName = tName.ToString() + "." + fName; } if (refObj.IsIndirect() && field == null) { iRef = (PRIndirectReference)refObj; field = (PRAcroForm.FieldInformation)refToField[iRef.Number]; } //refObj = (PdfObject)an.Get(PdfName.PARENT); an = (PdfDictionary)PdfReader.GetPdfObject((PdfObject)an.Get(PdfName.PARENT)); } if (fName.EndsWith(".")) { fName = fName.Substring(0, fName.Length - 1); } PDFFieldLocation tempLoc = new PDFFieldLocation(); ArrayList arr = rect.ArrayList; tempLoc.fieldName = fName; tempLoc.page = page; tempLoc.x1 = ((PdfNumber)PdfReader.GetPdfObject((PdfObject)arr[0])).FloatValue; tempLoc.y1 = ((PdfNumber)PdfReader.GetPdfObject((PdfObject)arr[1])).FloatValue; tempLoc.x2 = ((PdfNumber)PdfReader.GetPdfObject((PdfObject)arr[2])).FloatValue; tempLoc.y2 = ((PdfNumber)PdfReader.GetPdfObject((PdfObject)arr[3])).FloatValue; this.PFDlocs.Add(tempLoc); } } } catch (Exception e) { throw new Exception("Critical Exception in GetFormFields", e); } finally { if ((reader != null)) { reader.Close(); } } }
private void ConcatenateLabelPdfs(List <string> filenames) { //int pageOffset = 0; //ArrayList master = new ArrayList(); //int f = 0; //String outFile = args[args.length - 1]; List <string> inputFilepaths = filenames.ConvertAll(x => storeUrls.ShippingLabelFolderFileRoot + x); Document document = null; PdfCopy writer = null; //int pageOffset = 0; int fileIndex = 0; foreach (string inputFile in inputFilepaths) { PdfReader reader = new PdfReader(inputFile); reader.ConsolidateNamedDestinations(); int pageCount = reader.NumberOfPages; //pageOffset += pageCount; if (fileIndex == 0) { document = new Document(reader.GetPageSizeWithRotation(1)); writer = new PdfCopy(document, new FileStream(@"C:\WEB\DNNspot_DEV\DesktopModules\DNNspot-Store\ShippingLabels\bulk.pdf", FileMode.Create)); document.Open(); } PdfImportedPage page; for (int p = 0; p < pageCount; p++) { ++p; page = writer.GetImportedPage(reader, p); writer.AddPage(page); } PRAcroForm form = reader.AcroForm; if (form != null) { writer.CopyAcroForm(reader); } fileIndex++; } document.Close(); //while (f < args.length - 1) { // PdfReader reader = new PdfReader(args[f]); // reader.consolidateNamedDestinations(); // int n = reader.getNumberOfPages(); // List bookmarks = SimpleBookmark.getBookmark(reader); // if (bookmarks != null) { // if (pageOffset != 0) { // SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, // null); // } // master.addAll(bookmarks); // } // pageOffset += n; // if (f == 0) { // document = new Document(reader.getPageSizeWithRotation(1)); // writer = new PdfCopy(document, // new FileOutputStream(outFile)); // document.open(); // } // PdfImportedPage page; // for (int i = 0; i < n;) { // ++i; // page = writer.getImportedPage(reader, i); // writer.addPage(page); // } // PRAcroForm form = reader.getAcroForm(); // if (form != null) { // writer.copyAcroForm(reader); // } // f++; //} //if (!master.isEmpty()) { // writer.setOutlines(master); //} //document.close(); }
private void generatePDF(string BOMExcel) { string docName = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Name; try { Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; acDoc.Database.SaveAs(acDoc.Name, true, DwgVersion.Current, acDoc.Database.SecurityParameters); } catch (Exception ex) { Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(ex.ToString()); } if (AcadFunctions.AcadLayersList.Count > 0) { if (Layerlisodwg.Any(x => x.Include)) { InitializeLayouts(); Document docPublish = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; var lstLayers = Layerlisodwg.Where(x => x.Include && x.EntityAvail).Select(x => x).ToList(); ProgressHeaderPublisher.PublishData("Processing..."); ProgressStatusPublisher.PublishData(""); ProgressBarMaximumPublisher.PublishData(lstLayers.Count + 1); int cnt = 0; bool Page_1Available = false; if (lstLayers.ToList().Count > 0) { Page_1Available = lstLayers.Where(a => a.Include == true && (a.LayerName.Equals("PAGE_1", StringComparison.InvariantCultureIgnoreCase) || a.LayerName.Equals("PAGE1", StringComparison.InvariantCultureIgnoreCase))).Any(); } lstLayers.ToList().ForEach(x => { cnt++; ProgressHeaderPublisher.PublishData("Processing " + cnt + " of " + lstLayers.Count); ProgressStatusPublisher.PublishData("Publishing " + x.LayerName + "..."); if (x.Include) { var layerName = x.LayerName; OnOrOffParticularLayer(true, layerName, Page_1Available); docPublish.SendStringToExecute("zoom e ", true, false, true); Thread.Sleep(1000); new SingleSheetPdf(_pdfLocation, GetLayoutIdList(Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database)).PublishNew(_pdfLocation, x.LayerName); OnOrOffParticularLayer(false, layerName, Page_1Available); } ProgressValuePublisher.PublishData(1); }); SetDefaultLayout(docPublish); OffAllLayers(true); ProgressHeaderPublisher.PublishData("Processing...."); ProgressStatusPublisher.PublishData("Merging pdf"); try { string path = _pdfLocation; string[] pdfFiles = Directory.GetFiles(path, "*.pdf").Select(f => new FileInfo(f)).OrderBy(f => f.CreationTime).Select(d => d.FullName).ToArray(); var completedFiles = new List <string>(); docName = System.IO.Path.GetFileNameWithoutExtension(docName); foreach (var item in pdfFiles) { if (System.IO.Path.GetFileNameWithoutExtension(item).StartsWith(docName)) { var layer = Layerlisodwg.Where(y => y.Include && item.Contains(y.LayerName)).Select(y => y).FirstOrDefault(); if (layer != null) { completedFiles.Add(item); } } } statusText = "Appending BOM Spreadsheet to PDF... (Task 6 of 6)"; lblpbBarContent.Content = statusText; pbBar.Value = pbBar.Value + 10; DoEventsHandler.DoEvents(); // step 1: creation of a document-object iTextSharp.text.Document document = new iTextSharp.text.Document(); if (File.Exists(System.IO.Path.Combine(path, docName + ".pdf"))) { File.Delete(System.IO.Path.Combine(path, docName + ".pdf")); } if (completedFiles.Count > 0) { // step 2: we create a writer that listens to the document PdfCopy writer = new PdfCopy(document, new FileStream(System.IO.Path.Combine(path, docName + ".pdf"), FileMode.Create)); if (writer == null) { return; } // step 3: we open the document document.Open(); foreach (string fileName in completedFiles) { // we create a reader for a certain document PdfReader reader = new PdfReader(fileName); reader.ConsolidateNamedDestinations(); // step 4: we add content for (int i = 1; i <= reader.NumberOfPages; i++) { PdfImportedPage page = writer.GetImportedPage(reader, i); writer.AddPage(page); } PRAcroForm form = reader.AcroForm; if (form != null) { writer.CopyAcroForm(reader); } reader.Close(); } // step 5: we close the document and writer writer.Close(); document.Close(); if (System.IO.File.Exists(BOMExcel)) { String strDwgPDF = System.IO.Path.Combine(path, docName + ".pdf"); string strBOMPDF = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(BOMExcel), System.IO.Path.GetFileNameWithoutExtension(BOMExcel) + ".pdf"); string strResultPDF = System.IO.Path.Combine(path, docName + "_PROD.pdf"); string shellCommand = "C:\\ACAD2018_LivaNova\\Interface\\PDFTK.exe " + strDwgPDF + " " + strBOMPDF + " cat output " + strResultPDF; AcadCommands oAcad = new AcadCommands(); oAcad.ExecuteCommandSync(shellCommand); } foreach (var item in completedFiles) { try { if (System.IO.File.Exists(item)) { System.IO.File.Delete(item); } } catch { } } ProgressValuePublisher.PublishData(1); ProgressHeaderPublisher.PublishData("Processed " + cnt + " of " + lstLayers.Count); ProgressStatusPublisher.PublishData("Completed"); //MessageBox.Show("PDF Generation Completed", Title, MessageBoxButton.OK, MessageBoxImage.Information); //10-05-2018 if (System.IO.File.Exists(System.IO.Path.Combine(path, docName + "_PROD.pdf"))) { System.Diagnostics.Process.Start(System.IO.Path.Combine(path, docName + "_PROD.pdf")); //System.IO.File.Open(System.IO.Path.Combine(path, docName + ".pdf"), FileMode.Open); } } else { ProgressValuePublisher.PublishData(1); ProgressHeaderPublisher.PublishData("Processed " + cnt + " of " + lstLayers.Count); ProgressStatusPublisher.PublishData("Failed"); MessageBox.Show("Failed to merge pdf.", Title, MessageBoxButton.OK, MessageBoxImage.Information); } } catch (Exception ex) { } } else { MessageBox.Show("Atleast one layer should be selected.", Title, MessageBoxButton.OK, MessageBoxImage.Warning); } } }
/// ----------------------------------------------------------------------------- /// <summary> /// PDFファイルの結合(長3,長4の場合) /// WritePage = 0:全ページ、WritePage = 1:全ファイルの1ページのみ /// WritePage = 2(3...):全ファイルの1~2(1~3)ページ /// </summary> /// <param name="arySrcFilePath">入力ファイルパス</param> /// <param name="sJoinFilePath">結合ファイルパス</param> /// <param name="WritePage">結合ページ数</param> /// ----------------------------------------------------------------------------- private void fnJoinPdf(string[] arySrcFilePath, string sJoinFilePath, int WritePage) { Document doc = null; // 出力ファイルDocument PdfCopy copy = null; // 出力ファイルPdfCopy try { //------------------------------------------------------------------------------------- // ファイル件数分、ファイル結合 //------------------------------------------------------------------------------------- for (int i = 0; i < arySrcFilePath.Length; i++) { // リーダー取得 PdfReader reader = new PdfReader(arySrcFilePath[i]); // 入力ファイル1を出力ファイルの雛形にする if (i == 0) { // Document作成 doc = new Document(reader.GetPageSizeWithRotation(1)); // 出力ファイルPdfCopy作成 copy = new PdfCopy(doc, new FileStream(sJoinFilePath, FileMode.Create)); // 出力ファイルDocumentを開く doc.Open(); // 文章プロパティ設定 //doc.AddKeywords((string)reader.Info["Keywords"]); //doc.AddAuthor((string)reader.Info["Author"]); //doc.AddTitle((string)reader.Info["Title"]); //doc.AddCreator((string)reader.Info["Creator"]); //doc.AddSubject((string)reader.Info["Subject"]); } // 結合するPDFのページ数 if (WritePage == 0) { WritePage = reader.NumberOfPages; } if (WritePage > reader.NumberOfPages) { WritePage = reader.NumberOfPages; } // PDFコンテンツを取得、copyオブジェクトに追加 for (int iPageCnt = 1; iPageCnt <= WritePage; iPageCnt++) { PdfImportedPage page = copy.GetImportedPage(reader, iPageCnt); copy.AddPage(page); } // フォーム入力を結合 PRAcroForm form = reader.AcroForm; if (form != null) { copy.AddDocument(reader); } // リーダーを閉じる reader.Close(); } } catch { throw; } finally { if (copy != null) { copy.Close(); } if (doc != null) { doc.Close(); } } }
private void BtnGenerate_Click(object sender, RoutedEventArgs e) { //try //{//17-July-2018 // string[] existingPdfFiles = Directory.GetFiles(_pdfLocation, "*.pdf"); // if (existingPdfFiles != null) // if (existingPdfFiles.Count() > 0) // { // MessageBox.Show("Please delete all existing files in "+ _pdfLocation +" before generating PDF", Title, MessageBoxButton.OK, MessageBoxImage.Warning); // return; // } //} //catch { } string docName = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Name; try {//10-05-2018 Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; acDoc.Database.SaveAs(acDoc.Name, true, DwgVersion.Current, acDoc.Database.SecurityParameters); //Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database.Save(); } catch (Exception ex) { Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(ex.ToString()); } if (AcadFunctions.AcadLayersList.Count > 0) { if (Layerlisodwg.Any(x => x.Include)) { InitializeLayouts(); //Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.Open(docName); Document docPublish = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; //Layerlisodwg.Where(x => x.LayerName.Equals("TITLE_1", StringComparison.InvariantCultureIgnoreCase) || // x.LayerName.Equals("BORDER", StringComparison.InvariantCultureIgnoreCase)).ToList().ForEach(a => a.Include = true); var lstLayers = Layerlisodwg.Where(x => x.Include && x.EntityAvail).Select(x => x).ToList(); gridProcess.Visibility = System.Windows.Visibility.Visible; ProgressHeaderPublisher.PublishData("Processing..."); txtPercentage.Text = string.Empty; ProgressStatusPublisher.PublishData(""); ProgressBarMaximumPublisher.PublishData(lstLayers.Count + 1); pbStatus.Visibility = System.Windows.Visibility.Visible; txtPercentage.Visibility = System.Windows.Visibility.Visible; int cnt = 0; lstLayers.ToList().ForEach(x => { cnt++; ProgressHeaderPublisher.PublishData("Processing " + cnt + " of " + lstLayers.Count); ProgressStatusPublisher.PublishData("Publishing " + x.LayerName + "..."); if (x.Include)// && x.EntityAvail) { var layerName = x.LayerName; OnOrOffParticularLayer(true, layerName); docPublish.SendStringToExecute("zoom e ", true, false, true); Thread.Sleep(1000); //new SingleSheetPdf(_pdfLocation, GetLayoutIdList(Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database)).Publish(x.LayerName); new SingleSheetPdf(_pdfLocation, GetLayoutIdList(Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database)).PublishNew(_pdfLocation, x.LayerName); OnOrOffParticularLayer(false, layerName); } ProgressValuePublisher.PublishData(1); }); SetDefaultLayout(docPublish); OffAllLayers(true); ProgressHeaderPublisher.PublishData("Processing...."); ProgressStatusPublisher.PublishData("Merging pdf"); try { string path = _pdfLocation; string[] pdfFiles = Directory.GetFiles(path, "*.pdf"); var completedFiles = new List <string>(); docName = System.IO.Path.GetFileNameWithoutExtension(docName); foreach (var item in pdfFiles) { if (System.IO.Path.GetFileNameWithoutExtension(item).StartsWith(docName)) { var layer = Layerlisodwg.Where(y => y.Include && item.Contains(y.LayerName)).Select(y => y).FirstOrDefault(); if (layer != null) { completedFiles.Add(item); } } } // step 1: creation of a document-object iTextSharp.text.Document document = new iTextSharp.text.Document(); if (File.Exists(System.IO.Path.Combine(path, docName + ".pdf"))) { File.Delete(System.IO.Path.Combine(path, docName + ".pdf")); } if (completedFiles.Count > 0) { // step 2: we create a writer that listens to the document PdfCopy writer = new PdfCopy(document, new FileStream(System.IO.Path.Combine(path, docName + ".pdf"), FileMode.Create)); if (writer == null) { return; } // step 3: we open the document document.Open(); foreach (string fileName in completedFiles) { // we create a reader for a certain document PdfReader reader = new PdfReader(fileName); reader.ConsolidateNamedDestinations(); // step 4: we add content for (int i = 1; i <= reader.NumberOfPages; i++) { PdfImportedPage page = writer.GetImportedPage(reader, i); writer.AddPage(page); } PRAcroForm form = reader.AcroForm; if (form != null) { writer.CopyAcroForm(reader); } reader.Close(); } // step 5: we close the document and writer writer.Close(); document.Close(); foreach (var item in completedFiles) { try { if (System.IO.File.Exists(item)) { System.IO.File.Delete(item); } } catch { } } ProgressValuePublisher.PublishData(1); ProgressHeaderPublisher.PublishData("Processed " + cnt + " of " + lstLayers.Count); ProgressStatusPublisher.PublishData("Completed"); MessageBox.Show("PDF Generation Completed", Title, MessageBoxButton.OK, MessageBoxImage.Information); gridProcess.Visibility = System.Windows.Visibility.Collapsed; pbStatus.Visibility = System.Windows.Visibility.Collapsed; txtPercentage.Visibility = System.Windows.Visibility.Collapsed; //10-05-2018 if (System.IO.File.Exists(System.IO.Path.Combine(path, docName + ".pdf"))) { System.Diagnostics.Process.Start(System.IO.Path.Combine(path, docName + ".pdf")); //System.IO.File.Open(System.IO.Path.Combine(path, docName + ".pdf"), FileMode.Open); } } else { ProgressValuePublisher.PublishData(1); ProgressHeaderPublisher.PublishData("Processed " + cnt + " of " + lstLayers.Count); ProgressStatusPublisher.PublishData("Failed"); MessageBox.Show("Failed to merge pdf.", Title, MessageBoxButton.OK, MessageBoxImage.Information); gridProcess.Visibility = System.Windows.Visibility.Collapsed; pbStatus.Visibility = System.Windows.Visibility.Collapsed; txtPercentage.Visibility = System.Windows.Visibility.Collapsed; } } catch (Exception ex) { } } else { MessageBox.Show("Atleast one layer should be selected.", Title, MessageBoxButton.OK, MessageBoxImage.Warning); } } }
public static string CombineMultiplePDFs(List <Documentos> fileNames, string outFile, string NombreCarpeta, string NombreArchivo) { try { Document document = new Document(); PdfCopy writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create)); if (writer == null) { return(string.Empty); } document.Open(); foreach (Documentos documentt in fileNames) { var ext = Path.GetExtension(documentt.Url); switch (ext.ToLower()) { case ".pdf": PdfReader reader = new PdfReader(documentt.Url); reader.ConsolidateNamedDestinations(); // step 4: we add content for (int i = 1; i <= reader.NumberOfPages; i++) { PdfImportedPage page = writer.GetImportedPage(reader, i); writer.AddPage(page); } PRAcroForm form = reader.AcroForm; if (form != null) { writer.CopyDocumentFields(reader); } reader.Close(); break; case ".png": case ".jpeg": case ".jpg": case ".gif": Document doc = new Document(); string pdfFilePath = AppDomain.CurrentDomain.BaseDirectory + "Log\\Temp\\temp" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf"; PdfWriter writers = PdfWriter.GetInstance(doc, new FileStream(pdfFilePath, FileMode.Create)); doc.Open(); string imageURL = documentt.Url; iTextSharp.text.Image jpg; try { jpg = iTextSharp.text.Image.GetInstance(imageURL); } catch (Exception) { continue; } jpg.ScalePercent(24f); jpg.Alignment = Element.ALIGN_CENTER; doc.Add(jpg); doc.Close(); PdfReader readeri = new PdfReader(pdfFilePath); readeri.ConsolidateNamedDestinations(); // step 4: we add content for (int i = 1; i <= readeri.NumberOfPages; i++) { PdfImportedPage page = writer.GetImportedPage(readeri, i); writer.AddPage(page); } PRAcroForm formi = readeri.AcroForm; if (formi != null) { writer.CopyDocumentFields(readeri); } readeri.Close(); break; default: break; } } writer.Close(); document.Close(); var Archivo = System.IO.File.OpenRead(outFile); NombreArchivo = "E-" + NombreArchivo + "-" + String.Format("{0:s}", DateTime.Now); NombreCarpeta = "c-" + NombreCarpeta; string NombreArchivoReal = Archivo.Name; string[] ArrayExtension = NombreArchivoReal.Split('.'); string Extension = ArrayExtension[ArrayExtension.Length - 1]; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString")); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(NombreCarpeta); container.CreateIfNotExists(); container.SetPermissions( new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }); CloudBlockBlob blockBlob = container.GetBlockBlobReference(NombreArchivo + "." + Extension); blockBlob.DeleteIfExists(); blockBlob.UploadFromStream(Archivo); Archivo.Close(); DirectoryInfo di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "Log\\Temp"); foreach (FileInfo file in di.GetFiles()) { file.Delete(); } return(blockBlob.SnapshotQualifiedUri.AbsoluteUri); } catch (Exception ex) { throw; } }
public static void ConcatenatePdfFiles(List <string> fromFileNames, string toFileName) { var pageOffset = 0; var master = new ArrayList(); var f = 0; Document document = null /* TODO Change to default(_) if this is not a reference type */; PdfCopy writer = null /* TODO Change to default(_) if this is not a reference type */; foreach (var fromFileName in fromFileNames) { // we create a reader for a certain document var reader = new PdfReader(fromFileName); reader.ConsolidateNamedDestinations(); // we retrieve the total number of pages var numberOfPages = reader.NumberOfPages; var bookmarks = SimpleBookmark.GetBookmark(reader); if (bookmarks != null) { if (pageOffset != 0) { SimpleBookmark.ShiftPageNumbers(bookmarks, pageOffset, null); } master.AddRange(bookmarks); } pageOffset += numberOfPages; if (f == 0) { // step 1: creation of a document-object document = new Document(reader.GetPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document writer = new PdfCopy(document, new FileStream(toFileName, FileMode.Create)); // step 3: we open the document document.Open(); } // step 4: we add content PdfImportedPage page; int i = 0; while (i < numberOfPages) { i += 1; page = writer.GetImportedPage(reader, i); writer.AddPage(page); } PRAcroForm form = reader.AcroForm; if (form != null) { writer.CopyAcroForm(reader); } reader.Close(); f++; } // step 5: we close the document document.Close(); }
public object save() { string templateFile = "/Users/user/Downloads/1022out.pdf"; string outFile = "/Users/user/Downloads/1022out.html"; // ConvertPdfStreamToHtml(); iTextSharp.text.pdf.PdfReader pdfReader = null; PdfStamper pdfStamper = null; try { pdfReader = new iTextSharp.text.pdf.PdfReader(templateFile); PRAcroForm s = pdfReader.AcroForm; AcroFields pdfFormFields = pdfReader.AcroFields; foreach (var item in pdfFormFields.Fields) { var d = item.Value.GetMerged(0); int type = pdfFormFields.GetFieldType(item.Key); string aaac = pdfFormFields.GetField(item.Key); PRAcroForm.FieldInformation aaad = s.GetField(item.Key); PdfString aae = aaad.Info.GetAsString(PdfName.TU); if (aae == null) { continue; } // Console.WriteLine(item.Key+":"+type.ToString); Console.WriteLine("===={0},{1},{2},{3}===", item.Key, type, aaac, aae.ToString()); if (type == 2) { string[] aaa = pdfFormFields.GetAppearanceStates(item.Key); Console.WriteLine("{0}", string.Join(",", aaa)); } // PrintProperties(item); var str = d.Get(PdfName.V); if (!string.IsNullOrEmpty(str?.ToString())) { var p = (str.GetBytes()[0] << 8) + str.GetBytes()[1]; string code; switch (p) { case 0xefbb: code = "UTF-8"; break; case 0xfffe: code = "Unicode"; break; case 0xfeff: code = "UTF-16BE"; break; default: code = "GBK"; break; } var value = Encoding.GetEncoding(code).GetString(str.GetBytes()); Console.WriteLine(item.Key + ":" + value); } } } catch (Exception ex) { Console.WriteLine("" + ex.Message); } finally { if (pdfStamper != null) { pdfStamper.Close(); } if (pdfReader != null) { pdfReader.Close(); } } return(DateTime.Now); }
/// <summary> /// Merge multi pdfs into one pdf /// </summary> /// <param name="Pieces">ArrayList of Pdf byte()</param> /// <returns>Output Pdf byte()</returns> public byte[] MergePdf(List <byte[]> Pieces) { MemoryStream OutputStream = new MemoryStream(); if (Pieces.Count < 2) { //System.err.println("2 or more files are required"); throw new Exception("2 or more files are required."); } else { try { int pageOffset = 0; ArrayList master = new ArrayList(); int f = 0; //String outFile = this.rootPath + outputName; iTextSharp.text.Document document = null; PdfCopy writer = null; while (f < Pieces.Count) { // we create a reader for a certain document //ac.debugText("\nFile " + f + ": " + this.changeSlashType(pathType, (String)pieces.get(f))); //Dim reader As New PdfReader(TryCast(Pieces(f), byte())) PdfReader reader; if ((Pieces[f] != null)) { if (((!object.ReferenceEquals(Pieces[f].GetType(), typeof(int))))) { reader = new PdfReader((byte[])Pieces[f]); } else { break; } } else { break; } reader.ConsolidateNamedDestinations(); // we retrieve the total number of pages int n = reader.NumberOfPages; ArrayList bookmarks = SimpleBookmark.GetBookmark(reader); if ((bookmarks != null)) { if (pageOffset != 0) { SimpleBookmark.ShiftPageNumbers(bookmarks, pageOffset, null); } master.AddRange(bookmarks); } pageOffset += n; //ac.debugText("\n\nThere are " + n + " pages in " + this.changeSlashType(pathType, (String)pieces.get(f)) + "\n\n"); if (f == 0) { // step 1: creation of a document-object document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document writer = new PdfCopy(document, OutputStream); writer.CloseStream = false; // step 3: we open the document document.Open(); } // step 4: we add content int i = 0; while (i < n) { PdfImportedPage page; i += 1; page = writer.GetImportedPage(reader, i); //ac.debugText("Processed page " + i); writer.AddPage(page); } PRAcroForm form = reader.AcroForm; if ((form != null)) { writer.CopyAcroForm(reader); } f += 1; } if (master.Count > 0) { writer.Outlines = master; } // step 5: we close the document document.Close(); } catch (Exception e) { //e.printStackTrace(); //System.Diagnostics.Debug.WriteLine(e); throw new Exception("Crticial Exception in MergePdf", e); } } //OutputStream.Position = 0 return(OutputStream.ToArray()); }