public void Remove (PdfOutline outline) { if (outline == null) throw new ArgumentNullException("outline"); if (!outlines.Contains (outline)) throw new ArgumentException("outline not contained in this collection"); outlines.Remove (outline); this.Owner.irefTable.Remove(outline.Reference); }
internal PdfOutlineCollection(PdfDocument document, PdfOutline parent) : base(document) { this.parent = parent; }
internal PdfOutlineCollection(PdfDocument document, PdfOutline parent) : base(document) { this.parent = parent; var first = (PdfOutline)parent.Elements.GetValue (Keys.First); while (first != null) { first.Parent = parent; first.Document = parent.Owner; outlines.Add (first); first = (PdfOutline)first.Elements.GetValue (Keys.Next); } }
//Pre-Condition: // string destinationFile, the file which will be saved for output after merger // string[] sourceFiles, a string array of the location of the files to be merged // string[] pageName, a string array of the bookmark names for each pdf file to be merged //Post-Condition: // the seperate pdf files are merged with bookmarks added then saved to the destinationFile public static void MergeFiles(string destinationFile, string[] sourceFiles, string[] pageName) { int TotalPages = 0;//总页码 try { int f = 0; PdfReader reader = new PdfReader(sourceFiles[f]); int n = reader.NumberOfPages; TotalPages += n; Document document = new Document(reader.getPageSizeWithRotation(1)); PdfWriter writer = PdfWriter.getInstance(document, new FileStream(destinationFile, FileMode.Create)); //每列显示一页 //显示大纲 //页面大小适合窗口 writer.setViewerPreferences(PdfWriter.PageLayoutOneColumn | PdfWriter.PageModeUseOutlines | PdfWriter.FitWindow); document.Open(); PdfContentByte cb = writer.DirectContent; PdfImportedPage page; int rotation; int pdfPageName = 0; bool pdfNewPageFlag = true; while (f < sourceFiles.Length) { int i = 0; while (i < n)//n为当前导入文件的页数 { i++; //取得页面方向 document.setPageSize(reader.getPageSizeWithRotation(i)); //新建一页 document.newPage(); if (pdfNewPageFlag == true) { //建立转向标记 PdfAction a = PdfAction.gotoLocalPage(TotalPages, new PdfDestination(PdfDestination.FITH), writer); //建立在纲 PdfOutline outLine = new PdfOutline(writer.DirectContent.RootOutline, a, pageName[f]); pdfNewPageFlag = false; pdfPageName++; } page = writer.getImportedPage(reader, i); rotation = reader.getPageRotation(i); if (rotation == 90 || rotation == 270) { cb.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).Height); } else { cb.addTemplate(page, 1f, 0, 0, 1f, 0, 0); } } f++; if (f < sourceFiles.Length) { reader = new PdfReader(sourceFiles[f]); n = reader.NumberOfPages; TotalPages += n;//累计页码 pdfNewPageFlag = true; } } document.Close(); } catch { //Console.Error.WriteLine(e.Message); //Console.Error.WriteLine(e.StackTrace); } }
public void WriteTocEntries() { if (!Config.Current.ShowTOC) { return; } if (pdfWriter == null || pdfDocument == null) { Log.Error("Uninitialized property pdfWriter or pdfDocument. Pass valid values and try again"); return; } Log.Information("Writing Table of Contents ..."); int beforeToc = pdfWriter.CurrentPageNumber; pdfWriter.PageEvent = new TocFooterHandler() { StartPageIndex = beforeToc, TOCString = TABLEOFCONTENTS }; pdfDocument.NewPage(); PdfAction action = PdfAction.GotoLocalPage(pdfWriter.CurrentPageNumber, new PdfDestination(PdfDestination.FITH, 806), pdfWriter); PdfOutline gotoPage = new PdfOutline(pdfWriter.RootOutline, action, TABLEOFCONTENTS); pdfWriter.DirectContent.AddOutline(gotoPage); Paragraph ToCTitle = new Paragraph(TABLEOFCONTENTS, new Font(BaseFont.CreateFont(BaseFont.TIMES_BOLD, BaseFont.WINANSI, true), 20)); ToCTitle.SpacingAfter = 20; pdfDocument.Add(ToCTitle); Font tocFont = new Font(BaseFont.CreateFont(Path.Combine(Environment.SystemDirectory, "../fonts/arial.ttf"), BaseFont.IDENTITY_H, true), 12); foreach (TOCEntry tocEntry in TocEntries) { // Auto advance to next page float currentY = pdfWriter.GetVerticalPosition(false); if (currentY < 90) { pdfDocument.NewPage(); } // write toc entry title Paragraph a = new Paragraph(); Chunk c; if (tocEntry.Level <= Config.Current.TOCLevel) { c = new Chunk(string.Format("{0} {1}", tocEntry.Numbering, tocEntry.Title), tocFont); } else { c = new Chunk(tocEntry.Title, tocFont); } int destinationPage = tocEntry.PageNumber; PdfAction gotoDestination = PdfAction.GotoLocalPage(destinationPage, new PdfDestination(PdfDestination.FITH, 806), pdfWriter); c.SetAction(gotoDestination); a.Add(c); a.IndentationLeft = (tocEntry.Level - 1) * 20 + 60; a.FirstLineIndent = -40; a.IndentationRight = 30; pdfDocument.Add(a); // write toc entry page number currentY = pdfWriter.GetVerticalPosition(false); PdfContentByte cb = pdfWriter.DirectContent; cb.SaveState(); cb.BeginText(); BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); cb.SetFontAndSize(bf, 12); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, destinationPage.ToString(), pdfDocument.Right, currentY, 0); cb.EndText(); cb.RestoreState(); } Log.Information("Reordering pages ..."); int totalPages = pdfWriter.CurrentPageNumber; // now reorder the pages int[] reorder = new int[totalPages]; for (int i = 0; i < totalPages; i++) { reorder[i] = i + beforeToc + 1; if (reorder[i] > totalPages) { reorder[i] -= totalPages; } } pdfDocument.NewPage(); pdfWriter.PageEvent = null; pdfWriter.ReorderPages(reorder); Log.Information(string.Format("Number of pages for TOC is {0}", totalPages - beforeToc)); Log.Verbose("Set page labels"); PdfPageLabels pageLabels = new PdfPageLabels(); pageLabels.AddPageLabel(1, PdfPageLabels.LOWERCASE_ROMAN_NUMERALS); pageLabels.AddPageLabel(totalPages - beforeToc + 1, PdfPageLabels.DECIMAL_ARABIC_NUMERALS); pdfWriter.PageLabels = pageLabels; }
/// <summary> /// Adds the specified outline entry. /// </summary> /// <param name="title">The outline text.</param> /// <param name="destinationPage">The destination page.</param> /// <param name="opened">Specifies whether the node is displayed expanded (opened) or collapsed.</param> /// <param name="style">The font style used to draw the outline text.</param> public PdfOutline Add(string title, PdfPage destinationPage, bool opened, PdfOutlineStyle style) { PdfOutline outline = new PdfOutline(title, destinationPage, opened, style); Add(outline); return outline; }
/// <summary> /// Gets the index of the specified outline. /// </summary> public int IndexOf(PdfOutline item) { return this.outlines.IndexOf(item); }
TreeIter IterForBookmark(PdfOutline bookmark) { return(model.IterFor(bookmark)); }
TreeIter AddOutline(TreeIter parent, PdfOutline outline) { return(TreeIter.Zero.Equals(parent) ? model.AppendValues(GetValuesFor(outline)) : model.AppendValues(parent, GetValuesFor(outline))); }
//合并文件 #region public static MemoryStream MergeFiles(ArrayList sourceFiles, ArrayList pageName) { int f = 0; //生成数据流初始化 MemoryStream ms = new MemoryStream(); PdfReader reader = new PdfReader(sourceFiles[f].ToString()); int n = reader.NumberOfPages; Document document = new Document(reader.getPageSizeWithRotation(1)); //打开 Document 生成 PDF PdfWriter writer = PdfWriter.getInstance(document, ms); //每列显示一页,显示大纲,页面大小适合窗口 writer.setViewerPreferences(PdfWriter.PageLayoutOneColumn | PdfWriter.PageModeUseOutlines | PdfWriter.FitWindow); try { document.Open(); PdfContentByte cb = writer.DirectContent; PdfImportedPage page; int rotation; int curPage = 1;//页码 while (f < sourceFiles.Count) { ////建立转向标记 //PdfAction a = PdfAction.gotoLocalPage(curPage, new PdfDestination(PdfDestination.FITH), writer); //PdfOutline outLine = new PdfOutline(writer.DirectContent.RootOutline, a, pageName[f].ToString()); string bookmark = pageName[f].ToString(); if (f == 0) { //建立转向标记 PdfAction a = PdfAction.gotoLocalPage(curPage, new PdfDestination(PdfDestination.FITH), writer); PdfOutline outLine = new PdfOutline(writer.DirectContent.RootOutline, a, bookmark); } else { int index = sourceFiles[f - 1].ToString().LastIndexOf('\\'); string lastfileName = sourceFiles[f - 1].ToString().Substring(index + 1, 10); string fileName = sourceFiles[f].ToString().Substring(index + 1, 10); if (fileName.Substring(0, 2) == "AA") { if (lastfileName != fileName) { //建立转向标记 PdfAction a = PdfAction.gotoLocalPage(curPage, new PdfDestination(PdfDestination.FITH), writer); PdfOutline outLine = new PdfOutline(writer.DirectContent.RootOutline, a, bookmark); } } else { //建立转向标记 PdfAction a = PdfAction.gotoLocalPage(curPage, new PdfDestination(PdfDestination.FITH), writer); PdfOutline outLine = new PdfOutline(writer.DirectContent.RootOutline, a, bookmark); } } int i = 0; while (i < n)//n为当前导入文件的页数 { i++; //取得页面方向 document.setPageSize(reader.getPageSizeWithRotation(i)); //新建一页 document.newPage(); //if (i == 1) //{ // //建立转向标记 // PdfAction a = PdfAction.gotoLocalPage(curPage, new PdfDestination(PdfDestination.FITH), writer); // PdfOutline outLine = new PdfOutline(writer.DirectContent.RootOutline, a, pageName[f].ToString()); //} //string bookmark = pageName[f].ToString(); //if (f == 0) //{ // //建立转向标记 // PdfAction a = PdfAction.gotoLocalPage(curPage, new PdfDestination(PdfDestination.FITH), writer); // PdfOutline outLine = new PdfOutline(writer.DirectContent.RootOutline, a, bookmark); //} //else //{ // int index = sourceFiles[f - 1].ToString().LastIndexOf('\\'); // string lastfileName = sourceFiles[f - 1].ToString().Substring(index + 1, 10); // string fileName = sourceFiles[f].ToString().Substring(index + 1, 10); // if (fileName.Substring(0, 2) == "AA") // { // if (lastfileName != fileName) // { // //建立转向标记 // PdfAction a = PdfAction.gotoLocalPage(curPage, new PdfDestination(PdfDestination.FITH), writer); // PdfOutline outLine = new PdfOutline(writer.DirectContent.RootOutline, a, bookmark); // } // } // else // { // //建立转向标记 // PdfAction a = PdfAction.gotoLocalPage(curPage, new PdfDestination(PdfDestination.FITH), writer); // PdfOutline outLine = new PdfOutline(writer.DirectContent.RootOutline, a, bookmark); // } //} page = writer.getImportedPage(reader, i); rotation = reader.getPageRotation(i); if (rotation == 90 || rotation == 270) { cb.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).Height); } else { cb.addTemplate(page, 1f, 0, 0, 1f, 0, 0); } curPage++; } f++; //下一份文件 if (f < sourceFiles.Count) { string test = sourceFiles[f].ToString(); if (System.IO.File.Exists(sourceFiles[f].ToString())) { try { reader = new PdfReader(sourceFiles[f].ToString()); n = reader.NumberOfPages; } catch { } } } } } finally { document.Close(); } return(ms); }
// Add any bookmarks returned by the conversion process private static void addPDFBookmarks(String generatedFile, List <PDFBookmark> bookmarks, Hashtable options, PdfOutline parent) { var hasParent = parent != null; if ((Boolean)options["verbose"]) { Console.WriteLine("Adding {0} bookmarks {1}", bookmarks.Count, (hasParent ? "as a sub-bookmark" : "to the PDF")); } var srcPdf = hasParent ? parent.Owner : PdfReader.Open(generatedFile, PdfDocumentOpenMode.Modify); foreach (var bookmark in bookmarks) { var page = srcPdf.Pages[bookmark.page - 1]; // Work out what level to add the bookmark var outline = hasParent ? parent.Outlines.Add(bookmark.title, page) : srcPdf.Outlines.Add(bookmark.title, page); if (bookmark.children != null && bookmark.children.Count > 0) { addPDFBookmarks(generatedFile, bookmark.children, options, outline); } } if (!hasParent) { srcPdf.Save(generatedFile); } }
public void Finish(string outfilename, string annotate, bool numberPages, int startPageNum, PaginationFormatting.PaginationFormats paginationFormat) { this.outputDocument.Info.Author = this.Author; if (this.Subject.Length > 0) { this.outputDocument.Info.Subject = this.Subject; } if (this.Title.Length > 0) { this.outputDocument.Info.Title = this.Title; } PdfOutline outline = null; this.bm.WriteToDoc(ref outline, ref this.outputDocument, 0); #region Add Page Numbering XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode); XFont font = new XFont("Verdana", 9, XFontStyle.Bold, options); XStringFormat pageNumFormat = new XStringFormat(); pageNumFormat.Alignment = XStringAlignment.Far; pageNumFormat.LineAlignment = XLineAlignment.Far; XStringFormat annotateFormat = new XStringFormat(); annotateFormat.Alignment = XStringAlignment.Near; annotateFormat.LineAlignment = XLineAlignment.Far; XGraphics gfx; XRect box; int pageNumber = startPageNum; int pageCount = this.outputDocument.Pages.Count; foreach (PdfPage page in this.outputDocument.Pages) { // Get a graphics object for page gfx = XGraphics.FromPdfPage(page); if (numberPages == true) { box = page.MediaBox.ToXRect(); box.Inflate(-30, -20); string pageLabel = PaginationFormatting.GetFormattedPageString( startPageNum, pageNumber, pageCount, paginationFormat); gfx.DrawString( pageLabel, font, XBrushes.Black, box, pageNumFormat); } if (string.IsNullOrEmpty(annotate) == false) { box = page.MediaBox.ToXRect(); box.Inflate(-30, -20); gfx.DrawString(annotate, font, XBrushes.Black, box, annotateFormat); } ++pageNumber; } #endregion this.outputDocument.Save(outfilename); this.bm.Clear(); }
/// <summary> /// Will save the tree structure in the pdf file /// </summary> /// <param name="bListFilePages"></param> /// <param name="strOutputPath"></param> /// <returns></returns> public static bool SaveTreeStructureToPDFOld(Dictionary <int, Dictionary <string, string> > bListFilePages, string strOutputPath) { //TestCreatePDF(); //return false; bool bReturn = false; string strPreviousFile = "previous"; PdfReader reader = null; Document inputDocument = null; Document outputDocument = new Document(); PdfCopy pdfCopyProvider = null; PdfImportedPage importedPage = null; FileStream objFileStream = new System.IO.FileStream(strOutputPath, System.IO.FileMode.Create); PdfWriter pdfWriter = PdfWriter.GetInstance(outputDocument, objFileStream); outputDocument.Open(); pdfWriter.ViewerPreferences = PdfWriter.PageModeUseOutlines; PdfOutline rootOutline = null; int iCount = 0; // Iterate files for (int iIndex = 0; iIndex < bListFilePages.Count; iIndex++) { string strCurrentFile = "Current"; try { Dictionary <string, string> innerDictionary = bListFilePages.ElementAt(iIndex).Value;//.Value.ToString(); string strBookMarkName = innerDictionary.ElementAt(0).Key.ToString(); string tempPath = innerDictionary.ElementAt(0).Value.ToString(); if (tempPath.Length > 0) { string strFilePath; string strPageNumber; PdfPage page = null; int iPageNumber = 1; // For simplicity, I am assuming all the pages share the same size // and rotation as the first page: if (iCount == 0) { strCurrentFile = GetFirstFileFromTree(iIndex, bListFilePages); if (strCurrentFile != strPreviousFile) { if (reader != null) { reader.Close(); reader = null; } reader = new PdfReader(strCurrentFile); } inputDocument = new Document(reader.GetPageSizeWithRotation(iPageNumber)); // Initialize an instance of the PdfCopyClass with the source // document and an output file stream: pdfCopyProvider = new PdfCopy(inputDocument, objFileStream); inputDocument.Open(); iCount++; } int i = tempPath.IndexOf("#@$"); if (i != -1) { strFilePath = tempPath.Substring(0, i - 1); strPageNumber = tempPath.Substring(i + 3); strCurrentFile = strFilePath; if (strCurrentFile != strPreviousFile) { if (reader != null) { reader.Close(); reader = null; } reader = new PdfReader(strCurrentFile); } if (IsNumber(strPageNumber)) { if (strFilePath.Length > 0 && strPageNumber.Length > 0) { iPageNumber = Convert.ToInt16(strPageNumber); importedPage = pdfCopyProvider.GetImportedPage(reader, iPageNumber); pdfCopyProvider.Add(new Chunk("Chapter 1").SetLocalDestination("1")); pdfCopyProvider.AddPage(importedPage); } } //Set as previous file here strPreviousFile = strCurrentFile; } else { if (File.Exists(tempPath)) { if (tempPath != strPreviousFile) { if (reader != null) { reader.Close(); reader = null; } reader = new PdfReader(tempPath); } importedPage = pdfCopyProvider.GetImportedPage(reader, 1); pdfCopyProvider.AddPage(importedPage); //Set as previous file here strPreviousFile = tempPath; } else//Means that it is a foler { string strFile = GetFirstFileFromTree(iIndex, bListFilePages); if (strFile != strPreviousFile) { if (reader != null) { reader.Close(); reader = null; } reader = new PdfReader(strFile); } importedPage = pdfCopyProvider.GetImportedPage(reader, 1); pdfCopyProvider.AddPage(importedPage); //Set as previous file here strPreviousFile = strFile; } } if (strBookMarkName.Length > 0) { // Create first page PdfContentByte cb = pdfWriter.DirectContent; PdfOutline root = cb.RootOutline; ArrayList outlineCollection = root.Kids; PdfOutline outline = CheckIfOutlineISPresent(strBookMarkName, outlineCollection); if (rootOutline != null) { rootOutline = new PdfOutline(rootOutline, PdfAction.GotoLocalPage("2", false), strBookMarkName); } else { rootOutline = new PdfOutline(root, PdfAction.GotoLocalPage("1", false), "Chapter 1"); } } } } catch (Exception ex) { } } if (inputDocument.IsOpen()) { inputDocument.Close(); } if (inputDocument != null) { inputDocument = null; } if (outputDocument.IsOpen()) { outputDocument.Close(); } if (outputDocument != null) { outputDocument = null; } if (reader != null) { reader.Close(); reader = null; } if (objFileStream != null) { objFileStream.Close(); objFileStream = null; } try { //if (bReturn) // outputDocument.Save(strOutputPath); } catch (Exception ex) { //bReturn = false; //MessageBox.Show(ex.Message); } return(true); }
public static bool SaveTreeStructureToPDF(Dictionary <int, Dictionary <string, string> > bListFilePages, string strOutputPath) { bool bReturn = false; string strPreviousFile = "previous"; string strCurrentFile = "Current"; string OutPutfile = strOutputPath; PdfReader inputReader = null; PdfOutline outline = null; int iPageCount = 1; try { Document outputDoc = new Document(); using (MemoryStream ms = new MemoryStream()) { PdfWriter writer = PdfWriter.GetInstance(outputDoc, ms); outputDoc.Open(); outputDoc.AddDocListener(writer); for (int iIndex = 0; iIndex < bListFilePages.Count; iIndex++) { Dictionary <string, string> innerDictionary = bListFilePages.ElementAt(iIndex).Value;//.Value.ToString(); string strBookMarkName = innerDictionary.ElementAt(0).Key.ToString(); string tempPath = innerDictionary.ElementAt(0).Value.ToString(); if (tempPath.Length > 0) { string strFilePath; string strPageNumber; PdfImportedPage page = null; int iPageNumber = 1; int i = tempPath.IndexOf("#@$"); if (i != -1) { strFilePath = tempPath.Substring(0, i - 1); strPageNumber = tempPath.Substring(i + 3); strCurrentFile = strFilePath; if (strCurrentFile != strPreviousFile) { if (inputReader != null) { inputReader.Close(); inputReader = null; } inputReader = new PdfReader(strCurrentFile); } if (IsNumber(strPageNumber)) { if (strFilePath.Length > 0 && strPageNumber.Length > 0) { iPageNumber = Convert.ToInt16(strPageNumber); outputDoc.SetPageSize(inputReader.GetPageSize(iPageNumber)); PdfContentByte cb = writer.DirectContent; page = writer.GetImportedPage(inputReader, iPageNumber); ///creat bookmark here and add in template PdfOutline root = cb.RootOutline; ArrayList outlineCollection = root.Kids; outline = CheckIfOutlineISPresent(strBookMarkName, outlineCollection); if (outline == null) { outline = new PdfOutline(root, PdfAction.GotoLocalPage(iPageCount, new iTextSharp.text.pdf.PdfDestination(iTextSharp.text.pdf.PdfDestination.FITH), writer), strBookMarkName); } else { outline = new PdfOutline(outline, PdfAction.GotoLocalPage(iPageCount, new iTextSharp.text.pdf.PdfDestination(iTextSharp.text.pdf.PdfDestination.FITH), writer), strBookMarkName); } outputDoc.NewPage(); Rectangle psize = inputReader.GetPageSizeWithRotation(iPageNumber); switch (psize.Rotation) { case 0: cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); break; case 90: cb.AddTemplate(page, 0, -1f, 1f, 0, 0, psize.Height); break; case 180: cb.AddTemplate(page, -1f, 0, 0, -1f, 0, 0); break; case 270: cb.AddTemplate(page, 0, 1.0F, -1.0F, 0, psize.Width, 0); break; default: break; } iPageCount++; } } strPreviousFile = strCurrentFile; } else { if (File.Exists(tempPath)) { strCurrentFile = tempPath; } else { strCurrentFile = GetFirstFileFromTree(iIndex, bListFilePages); } if (!File.Exists(strCurrentFile)) { continue; } iPageNumber = 1; PdfContentByte cb = writer.DirectContent; ///creat bookmark here and add in template PdfOutline root = cb.RootOutline; ArrayList outlineCollection = root.Kids; outline = CheckIfOutlineISPresent(strBookMarkName, outlineCollection); if (outline == null) { outline = new PdfOutline(root, PdfAction.GotoLocalPage(iPageCount, new iTextSharp.text.pdf.PdfDestination(iTextSharp.text.pdf.PdfDestination.FITH), writer), strBookMarkName); } else { outline = new PdfOutline(outline, PdfAction.GotoLocalPage(iPageCount, new iTextSharp.text.pdf.PdfDestination(iTextSharp.text.pdf.PdfDestination.FITH), writer), strBookMarkName); } } } } if (inputReader != null) { inputReader.Close(); inputReader = null; } outputDoc.Close(); using (FileStream fs = new FileStream(OutPutfile, FileMode.Create)) { // this is the part stumping me; I need to use a PdfStamper to write // out some values to fields on the form AFTER the pages are removed. // This works, but there doesn't seem to be a form on the copied page... PdfStamper stamper = new PdfStamper(new PdfReader(ms.ToArray()), fs); // write out fields here... stamper.FormFlattening = true; stamper.SetFullCompression(); stamper.Close(); } bReturn = true; } } catch (Exception ex) { bReturn = false; } return(bReturn); }
//internal int CountOpen() //{ // int count = 0; // foreach (PdfOutline outline in this.outlines) // count += outline.CountOpen(); // return count; //} /// <summary> /// Adds the specified outline. /// </summary> public void Insert(PdfOutline outline, int position) { if (outline == null) throw new ArgumentNullException("outline"); if (!Object.ReferenceEquals(Owner, outline.DestinationPage.Owner)) throw new ArgumentException("Destination page must belong to this document."); // TODO check the parent problems... outline.Document = Owner; outline.parent = this.parent; if (position == -1) { this.outlines.Add(outline); } else { this.outlines.Insert (position, outline); } this.Owner.irefTable.Add(outline); if (outline.Opened) { outline = this.parent; while (outline != null) { outline.openCount++; outline = outline.parent; } } }
/** * Constructor. * @param level the level * @param outline the PdfOutline for this HeaderNode * @param parent the parent HeaderNode * */ public HeaderNode(int level, PdfOutline outline, HeaderNode parent) { this.level = level; this.outline = outline; this.parent = parent; }
public void Add(PdfOutline outline) { Insert (outline, -1); }
protected void buttonCreatePdf_Click(object sender, EventArgs e) { // create a PDF document PdfDocument document = new PdfDocument(); // set a demo serial number document.SerialNumber = "YCgJMTAE-BiwJAhIB-EhlWTlBA-UEBRQFBA-U1FOUVJO-WVlZWQ=="; // display the outlines when the document is opened document.Viewer.PageMode = PdfPageMode.Outlines; // create the true type fonts that can be used in document System.Drawing.Font sysFont = new System.Drawing.Font("Times New Roman", 10, System.Drawing.GraphicsUnit.Point); PdfFont pdfFont = document.CreateFont(sysFont); PdfFont pdfFontEmbed = document.CreateFont(sysFont, true); System.Drawing.Font sysFontBold = new System.Drawing.Font("Times New Roman", 12, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); PdfFont pdfFontBold = document.CreateFont(sysFontBold); PdfFont pdfFontBoldEmbed = document.CreateFont(sysFontBold, true); System.Drawing.Font sysFontBig = new System.Drawing.Font("Times New Roman", 16, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); PdfFont pdfFontBig = document.CreateFont(sysFontBig); PdfFont pdfFontBigEmbed = document.CreateFont(sysFontBig, true); // create a reference Graphics used for measuring System.Drawing.Bitmap refBmp = new System.Drawing.Bitmap(1, 1); System.Drawing.Graphics refGraphics = System.Drawing.Graphics.FromImage(refBmp); refGraphics.PageUnit = System.Drawing.GraphicsUnit.Point; // create page 1 PdfPage page1 = document.AddPage(); float crtXPos = 10; float crtYPos = 20; #region Create Table of contents // create table of contents title PdfText tableOfContentsTitle = new PdfText(crtXPos, crtYPos, "Table of Contents", pdfFontBigEmbed); page1.Layout(tableOfContentsTitle); // create a top outline for the table of contents PdfDestination tableOfContentsDest = new PdfDestination(page1, new System.Drawing.PointF(crtXPos, crtYPos)); document.CreateTopOutline("Table of Contents", tableOfContentsDest); // advance current Y position in page crtYPos += pdfFontBigEmbed.Size + 10; // create Chapter 1 in table of contents PdfText chapter1TocTitle = new PdfText(crtXPos + 30, crtYPos, "Chapter 1", pdfFontBoldEmbed); // layout the chapter 1 title in TOC page1.Layout(chapter1TocTitle); // get the bounding rectangle of the chapter 1 title in TOC System.Drawing.SizeF textSize = refGraphics.MeasureString("Chapter 1", sysFontBold); System.Drawing.RectangleF chapter1TocTitleRectangle = new System.Drawing.RectangleF(crtXPos + 30, crtYPos, textSize.Width, textSize.Height); // advance current Y position in page crtYPos += pdfFontEmbed.Size + 10; // create Subchapter 1 in table of contents PdfText subChapter11TocTitle = new PdfText(crtXPos + 60, crtYPos, "Subchapter 1", pdfFontEmbed); // layout the text page1.Layout(subChapter11TocTitle); // get the bounding rectangle of the subchapter 1 title in TOC textSize = refGraphics.MeasureString("Subchapter 1", sysFont); System.Drawing.RectangleF subChapter11TocTitleRectangle = new System.Drawing.RectangleF(crtXPos + 60, crtYPos, textSize.Width, textSize.Height); // advance current Y position in page crtYPos += pdfFontEmbed.Size + 10; // create Subchapter 2 in table of contents PdfText subChapter21TocTitle = new PdfText(crtXPos + 60, crtYPos, "Subchapter 2", pdfFontEmbed); // layout the text page1.Layout(subChapter21TocTitle); // get the bounding rectangle of the subchapter 2 title in TOC textSize = refGraphics.MeasureString("Subchapter 2", sysFont); System.Drawing.RectangleF subChapter21TocTitleRectangle = new System.Drawing.RectangleF(crtXPos + 60, crtYPos, textSize.Width, textSize.Height); // advance current Y position in page crtYPos += pdfFontEmbed.Size + 10; // create Chapter 2 in table of contents PdfText chapter2TocTitle = new PdfText(crtXPos + 30, crtYPos, "Chapter 2", pdfFontBoldEmbed); // layout the text page1.Layout(chapter2TocTitle); // get the bounding rectangle of the chapter 2 title in TOC textSize = refGraphics.MeasureString("Capter 2", sysFontBold); System.Drawing.RectangleF chapter2TocTitleRectangle = new System.Drawing.RectangleF(crtXPos + 30, crtYPos, textSize.Width, textSize.Height); // advance current Y position in page crtYPos += pdfFontEmbed.Size + 10; // create Subchapter 1 in table of contents PdfText subChapter12TocTitle = new PdfText(crtXPos + 60, crtYPos, "Subchapter 1", pdfFontEmbed); // layout the text page1.Layout(subChapter12TocTitle); // get the bounding rectangle of the subchapter 1 title in TOC textSize = refGraphics.MeasureString("Subchapter 1", sysFont); System.Drawing.RectangleF subChapter12TocTitleRectangle = new System.Drawing.RectangleF(crtXPos + 60, crtYPos, textSize.Width, textSize.Height); // advance current Y position in page crtYPos += pdfFontEmbed.Size + 10; // create Subchapter 2 in table of contents PdfText subChapter22TocTitle = new PdfText(crtXPos + 60, crtYPos, "Subchapter 2", pdfFontEmbed); // layout the text page1.Layout(subChapter22TocTitle); // get the bounding rectangle of the subchapter 2 title in TOC textSize = refGraphics.MeasureString("Subchapter 2", sysFont); System.Drawing.RectangleF subChapter22TocTitleRectangle = new System.Drawing.RectangleF(crtXPos + 60, crtYPos, textSize.Width, textSize.Height); // advance current Y position in page crtYPos += pdfFontEmbed.Size + 10; // create the website link in the table of contents PdfText visitWebSiteText = new PdfText(crtXPos + 30, crtYPos, "Visit HiQPdf Website", pdfFontEmbed); visitWebSiteText.ForeColor = System.Drawing.Color.Navy; // layout the text page1.Layout(visitWebSiteText); // get the bounding rectangle of the website link in TOC textSize = refGraphics.MeasureString("Visit HiQPdf Website", sysFont); System.Drawing.RectangleF visitWebsiteRectangle = new System.Drawing.RectangleF(crtXPos + 30, crtYPos, textSize.Width, textSize.Height); // create the link to website in table of contents document.CreateUriLink(page1, visitWebsiteRectangle, "http://www.hiqpdf.com"); // advance current Y position in page crtYPos += pdfFontEmbed.Size + 10; // create a text note at the end of TOC PdfTextNote textNote = document.CreateTextNote(page1, new System.Drawing.PointF(crtXPos + 10, crtYPos), "The table of contents contains internal links to chapters and subchapters"); textNote.IconType = PdfTextNoteIconType.Note; textNote.IsOpen = true; #endregion #region Create Chapter 1 content and the link from TOC // create page 2 PdfPage page2 = document.AddPage(); // create the Chapter 1 title PdfText chapter1Title = new PdfText(crtXPos, 10, "Chapter 1", pdfFontBoldEmbed); // layout the text page2.Layout(chapter1Title); // create the Chapter 1 root outline PdfDestination chapter1Destination = new PdfDestination(page2, new System.Drawing.PointF(crtXPos, 10)); PdfOutline chapter1Outline = document.CreateTopOutline("Chapter 1", chapter1Destination); chapter1Outline.TitleColor = System.Drawing.Color.Navy; // create the PDF link from TOC to chapter 1 document.CreatePdfLink(page1, chapter1TocTitleRectangle, chapter1Destination); #endregion #region Create Subchapter 1 content and the link from TOC // create the Subchapter 1 PdfText subChapter11Title = new PdfText(crtXPos, 300, "Subchapter 1 of Chapter 1", pdfFontEmbed); // layout the text page2.Layout(subChapter11Title); // create subchapter 1 child outline PdfDestination subChapter11Destination = new PdfDestination(page2, new System.Drawing.PointF(crtXPos, 300)); PdfOutline subchapter11Outline = document.CreateChildOutline("Subchapter 1", subChapter11Destination, chapter1Outline); // create the PDF link from TOC to subchapter 1 document.CreatePdfLink(page1, subChapter11TocTitleRectangle, subChapter11Destination); #endregion #region Create Subchapter 2 content and the link from TOC // create the Subchapter 2 PdfText subChapter21Title = new PdfText(crtXPos, 600, "Subchapter 2 of Chapter 1", pdfFontEmbed); // layout the text page2.Layout(subChapter21Title); // create subchapter 2 child outline PdfDestination subChapter21Destination = new PdfDestination(page2, new System.Drawing.PointF(crtXPos, 600)); PdfOutline subchapter21Outline = document.CreateChildOutline("Subchapter 2", subChapter21Destination, chapter1Outline); // create the PDF link from TOC to subchapter 2 document.CreatePdfLink(page1, subChapter21TocTitleRectangle, subChapter21Destination); #endregion #region Create Chapter 2 content and the link from TOC // create page 3 PdfPage page3 = document.AddPage(); // create the Chapter 2 title PdfText chapter2Title = new PdfText(crtXPos, 10, "Chapter 2", pdfFontBoldEmbed); // layout the text page3.Layout(chapter2Title); // create chapter 2 to outline PdfDestination chapter2Destination = new PdfDestination(page3, new System.Drawing.PointF(crtXPos, 10)); PdfOutline chapter2Outline = document.CreateTopOutline("Chapter 2", chapter2Destination); chapter2Outline.TitleColor = System.Drawing.Color.Green; // create the PDF link from TOC to chapter 2 document.CreatePdfLink(page1, chapter2TocTitleRectangle, chapter2Destination); #endregion #region Create Subchapter 1 content and the link from TOC // create the Subchapter 1 PdfText subChapter12Title = new PdfText(crtXPos, 300, "Subchapter 1 of Chapter 2", pdfFontEmbed); // layout the text page3.Layout(subChapter12Title); // create subchapter 1 child outline PdfDestination subChapter12Destination = new PdfDestination(page3, new System.Drawing.PointF(crtXPos, 300)); PdfOutline subchapter12Outline = document.CreateChildOutline("Subchapter 1", subChapter12Destination, chapter2Outline); // create the PDF link from TOC to subchapter 1 document.CreatePdfLink(page1, subChapter12TocTitleRectangle, subChapter12Destination); #endregion #region Create Subchapter 2 content and the link from TOC // create the Subchapter 2 PdfText subChapter22Title = new PdfText(crtXPos, 600, "Subchapter 2 of Chapter 2", pdfFontEmbed); // layout the text page3.Layout(subChapter22Title); // create subchapter 2 child outline PdfDestination subChapter22Destination = new PdfDestination(page3, new System.Drawing.PointF(crtXPos, 600)); PdfOutline subchapter22Outline = document.CreateChildOutline("Subchapter 2", subChapter22Destination, chapter2Outline); // create the PDF link from TOC to subchapter 2 document.CreatePdfLink(page1, subChapter22TocTitleRectangle, subChapter22Destination); #endregion // dispose the graphics used for measuring refGraphics.Dispose(); refBmp.Dispose(); try { // write the PDF document to a memory buffer byte[] pdfBuffer = document.WriteToMemory(); // inform the browser about the binary data format HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf"); // let the browser know how to open the PDF document and the file name HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment; filename=PdfOutlines.pdf; size={0}", pdfBuffer.Length.ToString())); // write the PDF buffer to HTTP response HttpContext.Current.Response.BinaryWrite(pdfBuffer); // call End() method of HTTP response to stop ASP.NET page processing HttpContext.Current.Response.End(); } finally { document.Close(); } }
/// <summary> /// Adds the specified outline entry. /// </summary> /// <param name="title">The outline text.</param> /// <param name="destinationPage">The destination page.</param> public PdfOutline Add(string title, PdfPage destinationPage) { PdfOutline outline = new PdfOutline(title, destinationPage); Add(outline); return outline; }
// internal static bool VerifyOutputFile(string outputFile) // { // if (outputFile == null || outputFile.Length < 3) { return false; } // // if (File.Exists(outputFile)) // { // if (OVERWITE_EXISTING_FILE) // { // try // { // var f = File.OpenWrite(outputFile); // f.Close(); // File.Delete(outputFile); // // logMsgFmtln("output file", "exists: overwrite allowed"); // return true; // } // catch (Exception ex) // { // logMsgFmtln("result", "fail - file is not accessible or is open elsewhere"); // return false; // } // } // else // { // logMsgFmtln("output file", "exists: overwrite disallowed"); // return false; // } // } // // logMsgFmtln("output file", "does not exists"); // return true; // } internal PdfDocument Merge(PdfMergeTree mergeTree) { listOptions(); // if (!VerifyOutputFile()) // { // throw new IOException("Invalid Output File"); // } PdfWriter writer = new PdfWriter(pdfMgr.OutputPathAndFile); destPdf = new PdfDocument(writer); destPdfOutlines = destPdf.GetOutlines(false); PdfMerger merger = new PdfMerger(destPdf, MERGE_TAGS, MERGE_BOOKMARKS); merger.SetCloseSourceDocuments(false); logMsgDbLn2(""); int pageCount = merge(merger, mergeTree.GetMergeItems, 1) - 1; logMsgFmtln("total page count", pageCount); if (pageCount < 1) { destPdf.Close(); return(null); } if (KEEP_IMPORT_BOOKMARKS && ADD_BOOKMARK_FOR_EACH_FILE) { // process and adjust bookmarks MergeOutlines(destPdf.GetOutlines(true).GetAllChildren(), mergeTree.GetMergeItems); } if (!(KEEP_IMPORT_BOOKMARKS && !ADD_BOOKMARK_FOR_EACH_FILE)) { // eliminate all of the current bookmarks destPdfOutlines = clearOutline(destPdf); } if (ADD_BOOKMARK_FOR_EACH_FILE) { // add the new bookmarks addOutline(mergeTree.GetMergeItems, destPdfOutlines, 0); } // all complete // leave open for further processing // destPdf.Close(); // return the final PDF document PdfCatalog destPdfCatalog = destPdf.GetCatalog(); destPdfCatalog.SetPageMode(PdfName.UseOutlines); destPdfCatalog.SetPageLayout(PdfName.SinglePage); destPdfCatalog.SetOpenAction(PdfExplicitDestination.CreateFit(1)); return(destPdf); }
public void Start() { // Create the anchor for all pdf objects CompressionConfig cc = RdlEngineConfig.GetCompression(); anchor = new PdfAnchor(cc != null); //Create a PdfCatalog string lang; if (r.ReportDefinition.Language != null) lang = r.ReportDefinition.Language.EvaluateString(this.r, null); else lang = null; catalog = new PdfCatalog(anchor, lang); //Create a Page Tree Dictionary pageTree = new PdfPageTree(anchor); //Create a Font Dictionary fonts = new PdfFonts(anchor); //Create a Pattern Dictionary patterns = new PdfPattern(anchor); //Create an Image Dictionary images = new PdfImages(anchor); //Create an Outline Dictionary outline = new PdfOutline(anchor); //Create the info Dictionary info = new PdfInfo(anchor); //Set the info Dictionary. info.SetInfo(r.Name, r.Author, r.Description, ""); // title, author, subject, company //Create a utility object pdfUtility = new PdfUtility(anchor); //write out the header int size = 0; if (r.ItextPDF) { PdfWriter writer = PdfWriter.GetInstance(pdfdocument, ms); pdfdocument.Open(); cb = writer.DirectContent; pdfdocument.AddAuthor(r.Author); pdfdocument.AddCreationDate(); pdfdocument.AddCreator("Majorsilence Reporting"); pdfdocument.AddSubject(r.Description); pdfdocument.AddTitle(r.Name); } else { tw.Write(pdfUtility.GetHeader("1.5", out size), 0, size); } // filesize = size; }
public Chap1107() { Console.WriteLine("Chapter 11 example 7: Outlines and Destinations"); // step 1: creation of a document-object Document document = new Document(); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("Chap1107.pdf", FileMode.Create)); // step 3: we open the document document.Open(); // step 4: we grab the ContentByte and do some stuff with it PdfContentByte cb = writer.DirectContent; // we create a PdfTemplate PdfTemplate template = cb.CreateTemplate(25, 25); // we add some crosses to visualize the destinations template.MoveTo(13, 0); template.LineTo(13, 25); template.MoveTo(0, 13); template.LineTo(50, 13); template.Stroke(); // we add the template on different positions cb.AddTemplate(template, 287, 787); cb.AddTemplate(template, 187, 487); cb.AddTemplate(template, 487, 287); cb.AddTemplate(template, 87, 87); // we define the destinations PdfDestination d1 = new PdfDestination(PdfDestination.XYZ, 300, 800, 0); PdfDestination d2 = new PdfDestination(PdfDestination.FITH, 500); PdfDestination d3 = new PdfDestination(PdfDestination.FITR, 200, 300, 400, 500); PdfDestination d4 = new PdfDestination(PdfDestination.FITBV, 100); PdfDestination d5 = new PdfDestination(PdfDestination.FIT); // we define the outlines PdfOutline out1 = new PdfOutline(cb.RootOutline, d1, "root"); PdfOutline out2 = new PdfOutline(out1, d2, "sub 1"); PdfOutline out3 = new PdfOutline(out1, d3, "sub 2"); PdfOutline out4 = new PdfOutline(out2, d4, "sub 2.1"); PdfOutline out5 = new PdfOutline(out2, d5, "sub 2.2"); cb.AddOutline(out1); cb.AddOutline(out2); cb.AddOutline(out3); cb.AddOutline(out4); cb.AddOutline(out5); } catch (DocumentException de) { Console.Error.WriteLine(de.Message); } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } // step 5: we close the document document.Close(); }