private void UpdateTargetPages(IList <Dictionary <string, object> > existingOutlines, Dictionary <int, int> reverseSortKeys) { if (existingOutlines == null) { return; } foreach (var outline in existingOutlines) { object oldPageTarget; outline.TryGetValue("Page", out oldPageTarget); if (oldPageTarget != null) { var oldPageNumber = int.Parse(((string)oldPageTarget).Split(' ')[0]); var newPageNumber = reverseSortKeys[oldPageNumber]; var shift = newPageNumber - oldPageNumber; var pageOutlines = new List <Dictionary <string, object> >(); pageOutlines.Add(outline); SimpleBookmark.ShiftPageNumbers(pageOutlines, shift, null); } else { System.Diagnostics.Debug.Print("No target page"); } object children; outline.TryGetValue("Kids", out children); UpdateTargetPages(children as IList <Dictionary <string, object> >, reverseSortKeys); } }
private static void MergePdfFiles(MemoryStream outputPdf, Stream[] sourcePdfs) { PdfReader reader = null; Document document = new Document(); PdfImportedPage page = null; PdfCopy pdfCpy = null; int n = 0; int totalPages = 0; int page_offset = 0; List <Dictionary <string, object> > bookmarks = new List <Dictionary <string, object> >(); IList <Dictionary <string, object> > tempBookmarks; for (int i = 0; i <= sourcePdfs.GetUpperBound(0); i++) { reader = new PdfReader(sourcePdfs[i]); reader.ConsolidateNamedDestinations(); n = reader.NumberOfPages; tempBookmarks = SimpleBookmark.GetBookmark(reader); if (i == 0) { document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1)); pdfCpy = new PdfCopy(document, outputPdf); document.Open(); SimpleBookmark.ShiftPageNumbers(tempBookmarks, page_offset, null); page_offset += n; if (tempBookmarks != null) { bookmarks.AddRange(tempBookmarks); } totalPages = n; } else { SimpleBookmark.ShiftPageNumbers(tempBookmarks, page_offset, null); if (tempBookmarks != null) { bookmarks.AddRange(tempBookmarks); } page_offset += n; totalPages += n; } for (int j = 1; j <= n; j++) { page = pdfCpy.GetImportedPage(reader, j); pdfCpy.AddPage(page); } reader.Close(); } pdfCpy.Outlines = bookmarks; document.Close(); }
// --------------------------------------------------------------------------- /** * Manipulates a PDF file src with the file dest as result * @param src the original PDF */ public byte[] ManipulatePdf(List <byte[]> src) { using (MemoryStream ms = new MemoryStream()) { // step 1 using (Document document = new Document()) { // step 2 using (PdfCopy copy = new PdfCopy(document, ms)) { // step 3 document.Open(); // step 4 int page_offset = 0; // Create a list for the bookmarks List <Dictionary <String, Object> > bookmarks = new List <Dictionary <String, Object> >(); for (int i = 0; i < src.Count; i++) { PdfReader reader = new PdfReader(src[i]); // merge the bookmarks IList <Dictionary <String, Object> > tmp = SimpleBookmark.GetBookmark(reader); SimpleBookmark.ShiftPageNumbers(tmp, page_offset, null); foreach (var d in tmp) { bookmarks.Add(d); } // add the pages int n = reader.NumberOfPages; page_offset += n; for (int page = 0; page < n;) { copy.AddPage(copy.GetImportedPage(reader, ++page)); } } // Add the merged bookmarks copy.Outlines = bookmarks; } } return(ms.ToArray()); } }
/* ----------------------------------------------------------------- */ /// /// GetBookmarks /// /// <summary> /// Gets the collection of bookmarks embedded in the specified /// PDF document. /// </summary> /// /// <param name="src">PdfReader object.</param> /// <param name="pagenum">Page number.</param> /// <param name="delta"> /// Difference in page numbers between PDF documents. /// </param> /// <param name="dest">Container for the result.</param> /// /// <remarks> /// PdfReader オブジェクトから取得されたしおり情報に対して、 /// ページ番号を delta だけずらした後に処理を実行します。 /// </remarks> /// /* ----------------------------------------------------------------- */ public static void GetBookmarks(this PdfReader src, int pagenum, int delta, IList <Dictionary <string, object> > dest) { var cmp = $"^{pagenum} (XYZ|Fit|FitH|FitBH)"; var bookmarks = SimpleBookmark.GetBookmark(src); if (bookmarks == null) { return; } SimpleBookmark.ShiftPageNumbers(bookmarks, delta, null); foreach (var b in bookmarks) { var found = b.TryGetValue("Page", out object obj); if (found && Regex.IsMatch(obj.ToString(), cmp)) { dest.Add(b); } } }
void AddBookmark(PdfReader reader, string pdfFilename, List <Dictionary <String, Object> > parentBookmarks) { // Get bookmark from PDF var childBookmark = SimpleBookmark.GetBookmark(reader); if (childBookmark != null) { // It has a bookmark SimpleBookmark.ShiftPageNumbers(childBookmark, pageCount, null); } else { // Create empty bookmark childBookmark = new List <Dictionary <String, Object> >(); } // Replace filename for bookmark string bookmarkFileName; if (replaceFileName.IsEnabled != false) { bookmarkFileName = Regex.Replace(pdfFilename, replaceFileName.Before, replaceFileName.After); } else { bookmarkFileName = Path.GetFileName(pdfFilename); } // Create filename bookmark var bookmarks = new List <Dictionary <string, object> >(); if (addFileNameToBookmark.IsEnabled == false) { if ((addFileNameToBookmark.ExclusionPattern != null) && Regex.IsMatch(pdfFilename, addFileNameToBookmark.ExclusionPattern)) { bookmarks.Add(CreateBookmark(bookmarkFileName, childBookmark)); } else { bookmarks.AddRange(childBookmark); } } else { if ((addFileNameToBookmark.ExclusionPattern != null) && (Regex.IsMatch(pdfFilename, addFileNameToBookmark.ExclusionPattern))) { bookmarks.AddRange(childBookmark); } else { bookmarks.Add(CreateBookmark(bookmarkFileName, childBookmark)); } } // Add bookmarks to parent bookmarks if (parentBookmarks == null) { rootBookmarks.AddRange(bookmarks); } else { parentBookmarks.AddRange(bookmarks); } }
private string[] SplitPdf(string url, string splittedFilesDirectoryName, string prefixOfFileName) { PdfReader reader = LibPDFTools.CreatePdfReader(url, QueryPassword, false); try { reader.ConsolidateNamedDestinations(); IList <Dictionary <string, object> > bookmarks = SimpleBookmark.GetBookmark(reader); int numberOfPages = reader.NumberOfPages; string[] splittedFiles = new string[numberOfPages]; Directory.CreateDirectory(splittedFilesDirectoryName); for (int i = 1; i <= numberOfPages; i++) { string splittedFile = Path.Combine(splittedFilesDirectoryName, prefixOfFileName + i.ToString("D10") + ".pdf"); splittedFiles[i - 1] = splittedFile; //extract bookmarks on the page IList <Dictionary <string, object> > bookmark = null; if (bookmarks != null) { bookmark = new List <Dictionary <string, object> >(bookmarks); int[] rs; rs = new int[4]; rs[0] = 1; rs[1] = i - 1; rs[2] = i + 1; rs[3] = numberOfPages; SimpleBookmark.EliminatePages(bookmark, rs); rs = new int[2]; rs[0] = rs[1] = i; SimpleBookmark.ShiftPageNumbers(bookmark, 1 - i, rs); } using (var document = new Document(reader.GetPageSizeWithRotation(i))) { using (var outStream = new FileStream(splittedFile, FileMode.Create, FileAccess.Write)) { using (var writer = new PdfCopy(document, outStream)) { document.Open(); PdfImportedPage page = writer.GetImportedPage(reader, i); writer.AddPage(page); if (bookmark != null) { writer.Outlines = bookmark; } writer.Close(); } outStream.Close(); } document.Close(); } } return(splittedFiles); } finally { reader.Close(); } }
private static void AddBookmarks(List <string> files, PdfCopy OutFile) { //{[Title, pagina uno]} //{[Page, 1 XYZ 0 0 null]} //{[Action, GoTo]} //{[Kids, System.Collections.Generic.List`1[System.Collections.Generic.Dictionary`2[System.String,System.Object]]]} // Create a list for the bookmarks List <Dictionary <String, Object> > bookmarks = new List <Dictionary <String, Object> >(); int page_offset = 0; PdfReader reader = null; try { for (int i = 0; i < files.Count; i++) { reader = new PdfReader(files[i]); // merge the bookmarks IList <Dictionary <String, Object> > tmp = SimpleBookmark.GetBookmark(reader); SimpleBookmark.ShiftPageNumbers(tmp, page_offset, null); if (Bookmarks == 1) { tmp = new List <Dictionary <String, Object> >() { new Dictionary <string, object>() { ["Title"] = $"{Path.GetFileNameWithoutExtension(files[i])}", ["Page"] = $"{page_offset+1}", ["Action"] = "GoTo", ["Kids"] = tmp } }; } if (tmp != null) { foreach (var d in tmp) { bookmarks.Add(d); } } // add the pages int n = reader.NumberOfPages; page_offset += n; } // Add the merged bookmarks OutFile.Outlines = bookmarks; LogHelper.Log("Bookmarks copied successfully", LogType.Successful); } catch (Exception e) { LogHelper.Log(e.ToString(), LogType.Error); } finally { reader?.Dispose(); } }
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 bool merge(object sender, DoWorkEventArgs e, PdfReader[] pr, string output_pdf, int progressbarmaxvalue, BackgroundWorker[] bgw, Label[] lbl, ProgressBar[] pgb, TableLayoutPanel tablelayoutpanel, Button[] btn, bool[] isused) { supporting_class sc = new supporting_class(); // PdfReader reader = null; Document document = new Document(); PdfImportedPage page = null; PdfCopy pdfCpy = null; int n = 0; int totalPages = 0; int page_offset = 0; int counter = 0; int progress = 0; bool canceled = false; // for (int i = 0; i <= sourcePdfs.Length - 1; i++) // reader = new PdfReader(sourcePdfs[0]); List <Dictionary <string, object> > bookmarks = new List <Dictionary <string, object> >(); IList <Dictionary <string, object> > tempBookmarks; try { foreach (PdfReader reader in pr) { reader.ConsolidateNamedDestinations(); n = reader.NumberOfPages; tempBookmarks = SimpleBookmark.GetBookmark(reader); if (counter == 0) { document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1)); pdfCpy = new PdfCopy(document, new FileStream(output_pdf, FileMode.Create)); document.Open(); SimpleBookmark.ShiftPageNumbers(tempBookmarks, page_offset, null); page_offset += n; if (tempBookmarks != null) { bookmarks.AddRange(tempBookmarks); } totalPages = n; counter++; } else { SimpleBookmark.ShiftPageNumbers(tempBookmarks, page_offset, null); if (tempBookmarks != null) { bookmarks.AddRange(tempBookmarks); } page_offset += n; totalPages += n; } for (int j = 1; j <= n; j++) { Application.DoEvents(); if (bgw[Convert.ToInt32(e.Argument)].CancellationPending == true) { e.Cancel = true; if (tablelayoutpanel.InvokeRequired) { // flowlayoutpanel1.Invoke((MethodInvoker)(() => flowlayoutpanel1.Controls.Remove(pgb[Convert.ToInt32(e.Argument)]))); canceled = true; tablelayoutpanel.Invoke((MethodInvoker)(() => lbl[Convert.ToInt32(e.Argument)].Text = "Merging Canceled")); tablelayoutpanel.Invoke((MethodInvoker)(() => btn[Convert.ToInt32(e.Argument)].Enabled = false)); // flowlayoutpanel1.Invoke((MethodInvoker)(() => flowlayoutpanel1.Controls.Remove(btn[Convert.ToInt32(e.Argument)]))); // isused[Convert.ToInt32(e.Argument)] = false; } break; } else { page = pdfCpy.GetImportedPage(reader, j); pdfCpy.AddPage(page); progress++; bgw[Convert.ToInt32(e.Argument)].ReportProgress(progress, e.Argument); } } reader.Close(); } pdfCpy.Outlines = bookmarks; document.Close(); // isused[Convert.ToInt32(e.Argument)] = false; if (tablelayoutpanel.InvokeRequired) { if (!canceled) { tablelayoutpanel.Invoke((MethodInvoker)(() => btn[Convert.ToInt32(e.Argument)].Enabled = false)); tablelayoutpanel.Invoke((MethodInvoker)(() => lbl[Convert.ToInt32(e.Argument)].Text = "Merging Successfull")); } } return(true); } catch (IOException ex) { if (tablelayoutpanel.InvokeRequired) { MessageBox.Show(ex.Message); tablelayoutpanel.Invoke((MethodInvoker)(() => btn[Convert.ToInt32(e.Argument)].Enabled = false)); tablelayoutpanel.Invoke((MethodInvoker)(() => lbl[Convert.ToInt32(e.Argument)].Text = "Merging UnSuccessfull")); } return(false); } catch (Exception ex) { if (tablelayoutpanel.InvokeRequired) { show_message_box(ex.ToString()); tablelayoutpanel.Invoke((MethodInvoker)(() => btn[Convert.ToInt32(e.Argument)].Enabled = false)); tablelayoutpanel.Invoke((MethodInvoker)(() => lbl[Convert.ToInt32(e.Argument)].Text = "Merging UnSuccessfull")); } return(false); } }
private void AppendMain(PdfReader reader, string title, PageRange[] pageRanges, PdfConcatenatorOption option) { bool addOutlines = option.AddOutlines; bool copyOutlines = option.CopyOutlines; int i; bool[] appendOrNots = new bool[reader.NumberOfPages + 1]; foreach (var pr in pageRanges) { for (int j = pr.StartPage; j <= pr.EndPage; j++) { appendOrNots[j] = true; } } int theFirstPage = 0; for (i = 1; i <= reader.NumberOfPages; i++) { if (appendOrNots[i]) { theFirstPage = i; break; } } if (theFirstPage == 0) { // There is no append paes. return; } if (!opened) { opened = true; document = new Document(reader.GetPageSizeWithRotation(theFirstPage)); writer = new PdfCopy(document, outStream); writer.SetMergeFields(); if (ownerPassword != null) { byte[] bytesUserPassword = userPassword == null ? null : Encoding.ASCII.GetBytes(userPassword); writer.SetEncryption(bytesUserPassword, Encoding.ASCII.GetBytes(ownerPassword), permissions, encryptionStrength); } writer.ViewerPreferences = this.viewerPreference; document.Open(); } if (bookmarks == null) { if (addOutlines || copyOutlines) { bookmarks = new List <Dictionary <string, object> >(); } } if (bookmarks != null) { Dictionary <string, object> m = null; if (addOutlines) { m = new Dictionary <string, object>(); m["Title"] = title; m["Action"] = "GoTo"; m["Page"] = currPageNum.ToString() + " " + option.FittingStyle; } if (copyOutlines) { var cpbookmarks = SimpleBookmark.GetBookmark(reader); if (cpbookmarks != null) { int[] elimPages = new int[2]; int[] shiftPages = new int[2]; shiftPages[1] = reader.NumberOfPages; for (int pageIndex = reader.NumberOfPages; pageIndex > 0; --pageIndex) { if (!appendOrNots[pageIndex]) { elimPages[0] = elimPages[1] = pageIndex; shiftPages[0] = pageIndex + 1; SimpleBookmark.EliminatePages(cpbookmarks, elimPages); SimpleBookmark.ShiftPageNumbers(cpbookmarks, -1, shiftPages); } } SimpleBookmark.ShiftPageNumbers(cpbookmarks, currPageNum - 1, null); if (m == null) { foreach (var c in cpbookmarks) { bookmarks.Add(c); } } else { m["Kids"] = cpbookmarks; } } } if (m != null) { bookmarks.Add(m); } } { var pages = new List <int>(); for (int ii = 1; ii < appendOrNots.Length; ii++) { if (appendOrNots[ii]) { pages.Add(ii); currPageNum++; } } reader.SelectPages(pages); writer.AddDocument(reader); } }
/// <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()); }