// --------------------------------------------------------------------------- /** * Manipulates a PDF file src with the file dest as result (localhost) * @param src the original PDF */ public byte[] ManipulatePdf(byte[] src) { // Create the reader PdfReader reader = new PdfReader(src); int n = reader.NumberOfPages; using (MemoryStream ms = new MemoryStream()) { // Create the stamper using (PdfStamper stamper = new PdfStamper(reader, ms)) { // Add JavaScript jsString = File.ReadAllText( Path.Combine(Utility.ResourceJavaScript, RESOURCE) ); stamper.JavaScript = jsString; // Create a Chunk with a chained action PdfContentByte canvas; Chunk chunk = new Chunk("print this page"); PdfAction action = PdfAction.JavaScript( "app.alert('Think before you print!');", stamper.Writer ); action.Next(PdfAction.JavaScript( "printCurrentPage(this.pageNum);", stamper.Writer )); action.Next(new PdfAction("http://www.panda.org/savepaper/")); chunk.SetAction(action); Phrase phrase = new Phrase(chunk); // Add this Chunk to every page for (int i = 0; i < n;) { canvas = stamper.GetOverContent(++i); ColumnText.ShowTextAligned( canvas, Element.ALIGN_RIGHT, phrase, 816, 18, 0 ); } } return(ms.ToArray()); } }
protected void btnexportpdf_Click(object sender, EventArgs e) { //string rpthtml = bindheader("", "6"); //Session["ctrl"] = divinvdetail; //string url = "printpdf.aspx"; //string s = "window.open('" + url + "', '_blank');"; //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "temp", "<script type='text/javascript'>" + s + "</script>", false); string filename = System.DateTime.UtcNow.ToFileTimeUtc() + ".pdf"; Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Server.MapPath("~/webfile/temp/" + filename), FileMode.Create)); document.Open(); writer.PageEvent = new myPDFpgHandler(); HTMLWorker hw = new HTMLWorker(document); string html = divinvdetail.InnerHtml.Replace("margin: 40px auto;", "margin: 0px auto;"); StringReader sr = new StringReader(divinvdetail.InnerHtml); iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, sr); if (divinvdetailpage2.InnerHtml.Trim() != "") { document.NewPage(); string htmlpage2 = divinvdetailpage2.InnerHtml.Replace("margin: 20px auto;", "margin: 0px auto;"); StringReader sr1 = new StringReader(htmlpage2); iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, sr1); } //hw.Parse(new StringReader(HTML)); document.Close(); writer.Close(); // ShowPdf(filename, filepath); PdfAction action = new PdfAction(PdfAction.PRINTDIALOG); string s = "window.open('webfile/temp/" + filename + "', '_blank');"; ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "temp", "<script type='text/javascript'>" + s + "</script>", false); }
public string Print(List <string> labelList) { if (!Directory.Exists("out-labels-A4")) { Directory.CreateDirectory("out-labels-A4"); } labelList = AdjustCount(labelList); var outputPath = string.Format("{0}\\{1:dd_MM_yyyy_hh_mm_ss}.pdf", "out-labels-A4", DateTime.Now); Document document = new Document(PageSize.A4, 25, 25, 65, 0); var writer = PdfWriter.GetInstance(document, new FileStream(outputPath, FileMode.Create)); document.AddTitle("Barcode generator"); document.AddAuthor("Dipak Baba"); document.AddCreator("http://www.sangeetacollection.com"); document.Open(); PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, 0, 0.92f); PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer); writer.SetOpenAction(action); PdfPTable table = new PdfPTable(4); table.HorizontalAlignment = Element.ALIGN_LEFT; table.WidthPercentage = 100; table.DefaultCell.Border = Rectangle.NO_BORDER; foreach (var item in labelList) { table.AddCell(CreateImageCell(item)); } document.Add(table); document.Close(); return(outputPath); }
/// <summary> /// 将html转化为PDF的字节流 /// </summary> /// <param name="html">原始Html</param> /// <param name="message">转化信息</param> /// <returns>返回PDF的字节流</returns> public static byte[] FromHTMLtoPDF(string html, out string message) { Document document = new Document(); MemoryStream m = new MemoryStream(); MemoryStream stream = new MemoryStream(); byte[] bytes = null; try { PdfWriter writer = PdfWriter.GetInstance(document, m); document.Open(); PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, document.PageSize.Height, 1f); Encoding charset = Encoding.GetEncoding("gb2312"); byte[] data = charset.GetBytes(html); stream.Write(data, 0, data.Length); stream.Position = 0; XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, stream, null, charset, new UnicodeFontFactory()); PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer); writer.SetOpenAction(action); document.Close(); bytes = m.GetBuffer(); message = "100|成功"; } catch (Exception e) { string err = "Invalid nested tag body found"; if (e.Message.Contains(err)) { message = "102|html元素没有闭合标签"; } else { message = "102|将html转换为pdf出错!"; } } finally { stream.Close(); m.Close(); } return(bytes); }
public virtual void SoundAndTwoNextJavaScriptActionTest() { String fileName = "soundAndTwoNextJavaScriptActionTest.pdf"; PdfDocument document = CreateDocument(new PdfWriter(destinationFolder + fileName), false); Stream @is = new FileStream(sourceFolder + "sample.aif", FileMode.Open, FileAccess.Read); PdfStream sound1 = new PdfStream(document, @is); sound1.Put(PdfName.R, new PdfNumber(32117)); sound1.Put(PdfName.E, PdfName.Signed); sound1.Put(PdfName.B, new PdfNumber(16)); sound1.Put(PdfName.C, new PdfNumber(1)); PdfAction action = PdfAction.CreateSound(sound1); action.Next(PdfAction.CreateJavaScript("this.setPageRotations(0,2,90)")); action.Next(PdfAction.CreateJavaScript("this.setPageRotations(0,2,180)")); document.GetPage(2).SetAdditionalAction(PdfName.O, action); document.Close(); NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(destinationFolder + fileName, sourceFolder + "cmp_" + fileName, destinationFolder, "diff_")); }
public virtual void SoundActionWithToLowVolumeTest() { PdfDocument document = CreateDocument(new PdfWriter(new MemoryStream()), false); Stream @is = new FileStream(sourceFolder + "sample.aif", FileMode.Open, FileAccess.Read); PdfStream sound1 = new PdfStream(document, @is); sound1.Put(PdfName.R, new PdfNumber(32117)); sound1.Put(PdfName.E, PdfName.Signed); sound1.Put(PdfName.B, new PdfNumber(16)); sound1.Put(PdfName.C, new PdfNumber(1)); try { document.GetPage(2).SetAdditionalAction(PdfName.O, PdfAction.CreateSound(sound1, -1.1f, false, false, false )); NUnit.Framework.Assert.Fail("Exception not thrown"); } catch (Exception e) { NUnit.Framework.Assert.AreEqual("volume", e.Message); } document.Close(); }
public virtual void SplitLinkTest01() { NUnit.Framework.Assert.That(() => { String outFileName = destinationFolder + "splitLinkTest01.pdf"; String cmpFileName = sourceFolder + "cmp_splitLinkTest01.pdf"; PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdfDocument); PdfAction action = PdfAction.CreateURI("http://itextpdf.com"); PdfLinkAnnotation annotation = new PdfLinkAnnotation(new Rectangle(1, 1)).SetAction(action); Link linkByAnnotation = new Link(LONG_TEXT, annotation); doc.Add(new Div().SetHeight(700).SetBackgroundColor(ColorConstants.RED)); // This paragraph is so long that it will be present on the first, second and third pages doc.Add(new Paragraph(linkByAnnotation)); doc.Close(); NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder )); } , NUnit.Framework.Throws.InstanceOf <NullReferenceException>()) ; }
public virtual void CanvasWithPageEnableTaggingTest01() { String testName = "canvasWithPageEnableTaggingTest01"; String @out = destinationFolder + testName + ".pdf"; String cmp = sourceFolder + "cmp_" + testName + ".pdf"; PdfDocument pdf = new PdfDocument(new PdfWriter(@out)); pdf.SetTagged(); PdfPage page = pdf.AddNewPage(); Rectangle pageSize = page.GetPageSize(); Rectangle rectangle = new Rectangle(pageSize.GetX() + 36, pageSize.GetTop() - 80, pageSize.GetWidth() - 72 , 50); iText.Layout.Canvas canvas = new iText.Layout.Canvas(page, rectangle); canvas.Add(new Paragraph(new Link("Google link!", PdfAction.CreateURI("https://www.google.com")).SetUnderline ().SetFontColor(ColorConstants.BLUE))); canvas.Close(); pdf.Close(); NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(@out, cmp, destinationFolder)); }
public void PrintPdf() { //Document iText_xls_2_pdf = new Document(PageSize.A4.Rotate()); //PdfWriter writer = PdfWriter.GetInstance(iText_xls_2_pdf, response.getOutputStream()); //iText_xls_2_pdf.Open(); //PdfAction action = new PdfAction(PdfAction.PRINTDIALOG); //writer.SetOpenAction(action); //iText_xls_2_pdf.Close(); using (MemoryStream stream = new MemoryStream()) { Document iText_xls_2_pdf = new Document(PageSize.A4.Rotate()); PdfWriter writer = PdfWriter.GetInstance(iText_xls_2_pdf, stream); iText_xls_2_pdf.Open(); PdfAction action = new PdfAction(PdfAction.PRINTDIALOG); writer.SetOpenAction(action); iText_xls_2_pdf.Close(); } }
protected internal virtual void ApplyAction(PdfDocument document) { PdfAction action = this.GetProperty <PdfAction>(Property.ACTION); if (action != null) { PdfLinkAnnotation link = new PdfLinkAnnotation(GetOccupiedArea().GetBBox()); link.SetAction(action); Border border = this.GetProperty <Border>(Property.BORDER); if (border != null) { link.SetBorder(new PdfArray(new float[] { 0, 0, border.GetWidth() })); } else { link.SetBorder(new PdfArray(new float[] { 0, 0, 0 })); } document.GetPage(GetOccupiedArea().GetPageNumber()).AddAnnotation(link); } }
public virtual void StructureDestination02Test() { String srcFile = sourceFolder + "customRolesMappingPdf2.pdf"; String outFile = destinationFolder + "structureDestination02Test.pdf"; String cmpFile = sourceFolder + "cmp_structureDestination02Test.pdf"; PdfDocument document = new PdfDocument(new PdfReader(srcFile), new PdfWriter(outFile)); PdfStructElem imgElement = new PdfStructElem((PdfDictionary)document.GetPdfObject(13)); PdfStructureDestination dest = PdfStructureDestination.CreateFit(imgElement); PdfPage secondPage = document.AddNewPage(); PdfPage thirdPage = document.AddNewPage(); PdfLinkAnnotation linkExplicitDest = new PdfLinkAnnotation(new Rectangle(35, 785, 160, 15)); PdfAction gotoStructAction = PdfAction.CreateGoTo(PdfExplicitDestination.CreateFit(thirdPage)); gotoStructAction.Put(PdfName.SD, dest.GetPdfObject()); linkExplicitDest.SetAction(gotoStructAction); secondPage.AddAnnotation(linkExplicitDest); document.Close(); NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFile, cmpFile, destinationFolder, "diff_" )); }
protected void ManipulatePdf(String dest) { PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest)); PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true); PdfButtonFormField button = PdfFormField.CreatePushButton(pdfDoc, new Rectangle(36, 700, 36, 30), "post", "POST"); button.SetBackgroundColor(ColorConstants.GRAY); button.SetValue("POST"); // The second parameter is optional, it declares which fields to include in the submission or which to exclude, // depending on the setting of the Include/Exclude flag. button.SetAction(PdfAction.CreateSubmitForm("http://itextpdf.com:8180/book/request", null, PdfAction.SUBMIT_HTML_FORMAT | PdfAction.SUBMIT_COORDINATES)); button.SetVisibility(PdfFormField.VISIBLE_BUT_DOES_NOT_PRINT); form.AddField(button); pdfDoc.Close(); }
protected void ManipulatePdf(String dest) { PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest)); Document doc = new Document(pdfDoc); PdfFont bold = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD); Link link = new Link("The Best iText Questions on StackOverflow", PdfAction.CreateURI("https://pages.itextpdf.com/ebook-stackoverflow-questions.html")); link.SetFont(bold); Paragraph p = new Paragraph("Download ") .Add(link) .Add(" and discover more than 200 questions and answers."); // Rotate the paragraph on 90 degrees and add it to the document. doc.ShowTextAligned(p, 30, 100, 1, TextAlignment.LEFT, VerticalAlignment.TOP, (float)Math.PI / 2); doc.Close(); }
public void AddSubmitButton() { Rectangle rect = new Rectangle(50, 50, 100, 10); PushbuttonField button = new PushbuttonField(writer, rect, "postSubmit") { FontSize = 8, BackgroundColor = BaseColor.LIGHT_GRAY, BorderColor = GrayColor.BLACK, BorderWidth = 1f, BorderStyle = PdfBorderDictionary.STYLE_BEVELED, TextColor = GrayColor.GREEN, Text = "Submit", Visibility = PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT }; PdfFormField field = button.Field; String javascript = "validate();"; field.Action = PdfAction.JavaScript(javascript, writer); stamper.AddAnnotation(field, 1); }
public virtual void CreatePdf(String dest) { PdfDocument pdf = new PdfDocument(new PdfWriter(dest)); Document document = new Document(pdf); PdfAction js = PdfAction.CreateJavaScript("app.alert('Boo!');"); PdfAnnotation la1 = ((PdfLinkAnnotation) new PdfLinkAnnotation(new Rectangle(0, 0, 0, 0)).SetHighlightMode( PdfAnnotation.HIGHLIGHT_INVERT).SetAction(js)).SetBorderStyle(PdfAnnotation.STYLE_UNDERLINE); Link link1 = new Link("here", (PdfLinkAnnotation)la1); document.Add(new Paragraph().Add("Click ").Add(link1).Add(" if you want to be scared.")); PdfAnnotation la2 = new PdfLinkAnnotation(new Rectangle(0, 0, 0, 0)).SetDestination(PdfExplicitDestination .CreateFit(2)).SetHighlightMode(PdfAnnotation.HIGHLIGHT_PUSH).SetBorderStyle(PdfAnnotation.STYLE_INSET ); Link link2 = new Link("next page", (PdfLinkAnnotation)la2); document.Add(new Paragraph().Add("Go to the ").Add(link2).Add(" if you're too scared.")); document.Add(new AreaBreak(AreaBreakType.NEXT_PAGE)); document.Add(new Paragraph().Add("There, there, everything is OK.")); document.Close(); }
protected void ManipulatePdf(String dest) { PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest)); Document doc = new Document(pdfDoc); for (int i = 0; i < 10; i++) { String title = "This is title " + i; Text text = new Text(title).SetFontSize(16); text.SetNextRenderer(new TOCTextRenderer(text)); doc.Add(new Paragraph(text)); for (int j = 0; j < 50; j++) { doc.Add(new Paragraph("Line " + j + " of title " + i)); } } doc.Add(new AreaBreak()); // Create a table of contents doc.Add(new Paragraph("Table of Contents").SetFontSize(16)); foreach (KeyValuePair <String, KeyValuePair <String, int> > entry in toc) { Text text = new Text(entry.Key); KeyValuePair <String, int> value = entry.Value; text.SetAction(PdfAction.CreateGoTo(value.Key)); Paragraph p = new Paragraph(text); p.AddTabStops(new TabStop(750, TabAlignment.RIGHT, new DottedLine())); p.Add(new Tab()); text = new Text(value.Value.ToString()); text.SetAction(PdfAction.CreateGoTo(value.Key)); p.Add(text); doc.Add(p); } doc.Close(); }
// --------------------------------------------------------------------------- /** * Manipulates a PDF file src with the file dest as result (localhost) * @param src the original PDF */ public byte[] ManipulatePdf(byte[] src) { // Create the reader PdfReader reader = new PdfReader(src); int n = reader.NumberOfPages; using (MemoryStream ms = new MemoryStream()) { // Create the stamper using (PdfStamper stamper = new PdfStamper(reader, ms)) { // Get the writer (to add actions and annotations) PdfWriter writer = stamper.Writer; PdfAction action = PdfAction.GotoLocalPage(2, new PdfDestination(PdfDestination.FIT), writer ); writer.SetOpenAction(action); action = PdfAction.JavaScript( "app.alert('Think before you print');", writer ); writer.SetAdditionalAction(PdfWriter.WILL_PRINT, action); action = PdfAction.JavaScript( "app.alert('Think again next time!');", writer ); writer.SetAdditionalAction(PdfWriter.DID_PRINT, action); action = PdfAction.JavaScript( "app.alert('We hope you enjoy the festival');", writer ); writer.SetAdditionalAction(PdfWriter.DOCUMENT_CLOSE, action); action = PdfAction.JavaScript( "app.alert('This day is reserved for people with an accreditation " + "or an invitation.');", writer ); stamper.SetPageAction(PdfWriter.PAGE_OPEN, action, 1); action = PdfAction.JavaScript( "app.alert('You can buy tickets for all the other days');", writer ); stamper.SetPageAction(PdfWriter.PAGE_CLOSE, action, 1); } return(ms.ToArray()); } }
public byte[] ConvertHtmlTextToPDF(string htmlText, string styleCss) { if (string.IsNullOrEmpty(htmlText)) { return(null); } //避免当htmlText无任何html tag标签的纯文字时,转PDF时会挂掉,所以一律加上<p>标签 htmlText = "<p>" + htmlText + "</p>"; MemoryStream outputStream = new MemoryStream(); //要把PDF写到哪个串流 byte[] data = Encoding.UTF8.GetBytes(htmlText); //字串转成byte[] MemoryStream msInput = new MemoryStream(data); byte[] dataCss = Encoding.UTF8.GetBytes(styleCss);//字串转成byte[] MemoryStream cssStream = new MemoryStream(dataCss); Document doc = new Document();//要写PDF的文件,建构子没填的话预设直式A4 PdfWriter writer = PdfWriter.GetInstance(doc, outputStream); PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f); //开启Document文件 doc.Open(); //HeaderAndFooterEvent header = new HeaderAndFooterEvent(); //header.tpl = writer.DirectContent.CreateTemplate(100, 100); //writer.PageEvent = header; //使用XMLWorkerHelper把Html parse到PDF档里 XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, cssStream, Encoding.UTF8, new UnicodeFontFactory()); //将pdfDest设定的资料写到PDF档 PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer); writer.SetOpenAction(action); doc.Close(); msInput.Close(); cssStream.Close(); outputStream.Close(); //回传PDF档案 return(outputStream.ToArray()); }
public void pPDF() { //Open existing PDF Document document = new Document(PageSize.LETTER); PdfReader reader = new PdfReader(Server.MapPath("~/Report/nasser7.pdf")); //Getting a instance of new PDF writer PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Server.MapPath("~/Report/nasser12.pdf"), FileMode.Create)); document.Open(); PdfContentByte cb = writer.DirectContent; int i = 0; int p = 0; int n = reader.NumberOfPages; Rectangle psize = reader.GetPageSize(1); float width = psize.Width; float height = psize.Height; //Add Page to new document while (i < n) { document.NewPage(); p += 1; i += 1; PdfImportedPage page1 = writer.GetImportedPage(reader, i); cb.AddTemplate(page1, 0, 0); } //Attach javascript to the document PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer); writer.AddJavaScript(jAction); document.Close(); //Attach pdf to the iframe //frmPrint.Attributes("src") = "Print2.pdf"; }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 Image img = Image.GetInstance(IMG_BOX); document.Add(img); List list = new List(List.UNORDERED, 20); PdfDestination dest = new PdfDestination(PdfDestination.FIT); dest.AddFirst(new PdfNumber(1)); IEnumerable <Movie> box = PojoFactory.GetMovies(1) .Concat(PojoFactory.GetMovies(4)) ; foreach (Movie movie in box) { if (movie.Year > 1960) { PdfFileSpecification fs = PdfFileSpecification.FileEmbedded( writer, null, String.Format("kubrick_{0}.pdf", movie.Imdb), CreateMoviePage(movie) ); fs.AddDescription(movie.Title, false); writer.AddFileAttachment(fs); ListItem item = new ListItem(movie.MovieTitle); PdfTargetDictionary target = new PdfTargetDictionary(true); target.EmbeddedFileName = movie.Title; PdfAction action = PdfAction.GotoEmbedded(null, target, dest, true); Chunk chunk = new Chunk(" (see info)"); chunk.SetAction(action); item.Add(chunk); list.Add(item); } } document.Add(list); } }
private byte[] AddInfo(string msg, Stream input, bool print = false) { using (MemoryStream ms = new MemoryStream()) { using (PdfReader reader = new PdfReader(input)) using (PdfStamper stamper = new PdfStamper(reader, ms)) { for (int i = 1; i <= reader.NumberOfPages; i++) { Rectangle pageSize = reader.GetPageSize(i); float Rightx = pageSize.Width; float Righty = 0; float Centerx = pageSize.Width / 2; //float Centery = 0; float Leftx = 0; float Lefty = 0; PdfContentByte ContentByte = stamper.GetOverContent(i); if (print) { // Insert JavaScript to print the document after a fraction of a second (allow time to become visible). string jsText = "var res = app.setTimeOut('var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);', 200);"; //string jsTextNoWait = "var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);"; PdfAction js = PdfAction.JavaScript(jsText, stamper.Writer); stamper.Writer.AddJavaScript(js); } //var downloads = "# " + downloads.ToString(); AddQRCode(ContentByte, msg, Rightx, Righty, 3); //AddText(ContentByte, "# " + downloads.ToString(), Centerx, Centery, 3); AddTimeStamp(ContentByte, Leftx, Lefty, 3); } } return(ms.ToArray()); } }
protected void ManipulatePdf(String dest) { PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest)); Document doc = new Document(pdfDoc); Paragraph p = new Paragraph("Objects with links"); p.Add(CreateImage(INFO, "https://itextpdf.com/")); p.Add(CreateImage(DOG, "https://pages.itextpdf.com/ebook-stackoverflow-questions.html")); p.Add(CreateImage(FOX, "https://stackoverflow.com/q/29388313/1622493")); // Create PdfFormXObject object to add .wmf format image to the document, // because the creation of an ImageData instance from .wmf format image isn't supported. PdfFormXObject wmfImage = new PdfFormXObject(new WmfImageData(BUTTERFLY), pdfDoc); p.Add(new Image(wmfImage) .SetAction(PdfAction.CreateURI("https://stackoverflow.com/questions/tagged/itext*"))); doc.Add(p); doc.Close(); }
// --------------------------------------------------------------------------- /** * Show keys and values passed to the query string with GET */ protected void DoGet(byte[] pdf, Stream stream) { // We get a resource from our web app PdfReader reader = new PdfReader(pdf); // Now we create the PDF using (PdfStamper stamper = new PdfStamper(reader, stream)) { // We add a submit button to the existing form PushbuttonField button = new PushbuttonField( stamper.Writer, new Rectangle(90, 660, 140, 690), "submit" ); button.Text = "POST"; button.BackgroundColor = new GrayColor(0.7f); button.Visibility = PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT; PdfFormField submit = button.Field; submit.Action = PdfAction.CreateSubmitForm( WebContext.Request.RawUrl, null, PdfAction.SUBMIT_HTML_FORMAT ); stamper.AddAnnotation(submit, 1); } }
private void PDFCombineSection(PdfOutline parent, Data.ONSection section) { if (section == null) { throw new ArgumentNullException("section"); } if (section.Exclude) { return; } int currentPage = (pdfWriter.CurrentPageNumber == 1) ? pdfWriter.CurrentPageNumber : (pdfWriter.CurrentPageNumber + 1); PdfAction action = PdfAction.GotoLocalPage(currentPage, new PdfDestination(PdfDestination.FITH, 806), pdfWriter); PdfOutline gotoPage = new PdfOutline(parent, action, section.Name); //TODO: fix this // pdfWriter.DirectContent.AddOutline(gotoPage, gotoPage.Title); foreach (Data.ONSection subSection in section.SubSections) { if (!subSection.Exclude) { TOCHandler.AddTocEntry(subSection.Name, pdfWriter.CurrentPageNumber); TOCHandler.BeginTocEntry(); PDFCombineSection(gotoPage, subSection); TOCHandler.EndTocEntry(); } } foreach (Data.ONPage page in section.Pages) { if (pdfWriter.CurrentPageNumber == 1) { TOCHandler.AddTocEntry(page.Name, pdfWriter.CurrentPageNumber); } else { TOCHandler.AddTocEntry(page.Name, pdfWriter.CurrentPageNumber + 1); } PDFCombinePage(gotoPage, page); } }
// --------------------------------------------------------------------------- /** * Creates the PDF. * @return the bytes of a PDF file. */ public byte[] CreateMoviePage(Movie movie) { using (MemoryStream ms = new MemoryStream()) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, ms); // step 3 document.Open(); // step 4 Paragraph p = new Paragraph( movie.MovieTitle, FontFactory.GetFont( BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED, 16 ) ); document.Add(p); document.Add(Chunk.NEWLINE); PdfPTable table = new PdfPTable(WIDTHS); table.AddCell(Image.GetInstance( String.Format(RESOURCE, movie.Imdb) )); PdfPCell cell = new PdfPCell(); cell.AddElement(new Paragraph("Year: " + movie.Year.ToString())); cell.AddElement(new Paragraph("Duration: " + movie.Duration.ToString())); table.AddCell(cell); document.Add(table); PdfTargetDictionary target = new PdfTargetDictionary(false); target.AdditionalPath = new PdfTargetDictionary(false); Chunk chunk = new Chunk("Go to original document"); PdfAction action = PdfAction.GotoEmbedded( null, target, new PdfString("movies"), false ); chunk.SetAction(action); document.Add(chunk); } return(ms.ToArray()); } }
private static PdfPTable GenerateTableOfContents(PdfEvents tocEvent, PdfStamper stamper, int tocSize) { var tableOfContents = new PdfPTable(2); tableOfContents.SetWidths(new[] { 10, 1 }); tableOfContents.WidthPercentage = 100; tableOfContents.DefaultCell.Border = Rectangle.NO_BORDER; foreach (var item in tocEvent.Toc) { tableOfContents.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; tableOfContents.DefaultCell.PaddingLeft = 10 * (item.Level - 1); Font font; if (item.Level == 0) { tableOfContents.DefaultCell.PaddingBottom = 10; tableOfContents.DefaultCell.PaddingTop = 10; font = PdfFonts.Bold; } else { tableOfContents.DefaultCell.PaddingBottom = 2; tableOfContents.DefaultCell.PaddingTop = 2; font = PdfFonts.Normal; } var chunk = new Chunk(item.Title, font); var action = PdfAction.GotoLocalPage(item.Page, new PdfDestination(PdfDestination.FIT), stamper.Writer); chunk.SetAction(action); tableOfContents.AddCell(new Phrase(chunk)); tableOfContents.DefaultCell.PaddingLeft = 0; tableOfContents.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT; chunk = new Chunk(string.Format("{0}", item.Page + tocSize), font); tableOfContents.AddCell(new Phrase(chunk)); } return(tableOfContents); }
public virtual void LinkTest03() { String outFileName = destinationFolder + "linkTest03.pdf"; String cmpFileName = sourceFolder + "cmp_linkTest03.pdf"; PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName)); Document doc = new Document(pdfDoc); PdfArray array = new PdfArray(); array.Add(doc.GetPdfDocument().AddNewPage().GetPdfObject()); array.Add(PdfName.XYZ); array.Add(new PdfNumber(36)); array.Add(new PdfNumber(100)); array.Add(new PdfNumber(1)); PdfDestination dest = PdfDestination.MakeDestination(array); Link link = new Link("TestLink", dest); link.SetAction(PdfAction.CreateURI("http://itextpdf.com/", false)); doc.Add(new Paragraph(link)); doc.Close(); NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFileName, cmpFileName, destinationFolder , "diff")); }
protected void ManipulatePdf(String dest) { PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest)); Document doc = new Document(pdfDoc); // Make the link destination page fit to the display PdfExplicitDestination destination = PdfExplicitDestination.CreateFit(pdfDoc.GetPage(3)); Link link = new Link( "This is a link. Click it and you'll be forwarded to another page in this document.", // Add link to the 3rd page. PdfAction.CreateGoTo(destination)); // Set highlighting type which is enabled after a click on the annotation link.GetLinkAnnotation().SetHighlightMode(PdfAnnotation.HIGHLIGHT_INVERT); Paragraph p = new Paragraph(link).SetWidth(240); doc.ShowTextAligned(p, 320, 695, 1, TextAlignment.LEFT, VerticalAlignment.TOP, 0); doc.Close(); }
public virtual void ActionCheck15() { String outPdf = destinationFolder + "pdfA2b_actionCheck15.pdf"; String cmpPdf = sourceFolder + "cmp/PdfA2ActionCheckTest/cmp_pdfA2b_actionCheck15.pdf"; PdfWriter writer = new PdfWriter(outPdf); Stream @is = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read); PdfADocument doc = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_2B, new PdfOutputIntent("Custom", "" , "http://www.color.org", "sRGB IEC61966-2.1", @is)); doc.GetOutlines(true); PdfOutline @out = doc.GetOutlines(false); @out.AddOutline("New").AddAction(PdfAction.CreateGoTo("TestDest")); doc.AddNewPage(); doc.Close(); String result = new CompareTool().CompareByContent(outPdf, cmpPdf, destinationFolder, "diff_"); if (result != null) { NUnit.Framework.Assert.Fail(result); } }
public virtual void DestTest01() { String srcFile = sourceFolder + "simpleNoLinks.pdf"; String outFile = destinationFolder + "destTest01.pdf"; String cmpFile = sourceFolder + "cmp_destTest01.pdf"; PdfDocument document = new PdfDocument(new PdfReader(srcFile), new PdfWriter(outFile)); PdfPage firstPage = document.GetPage(1); PdfLinkAnnotation linkExplicitDest = new PdfLinkAnnotation(new Rectangle(35, 785, 160, 15)); linkExplicitDest.SetAction(PdfAction.CreateGoTo(PdfExplicitDestination.CreateFit(document.GetPage(2)))); firstPage.AddAnnotation(linkExplicitDest); PdfLinkAnnotation linkStringDest = new PdfLinkAnnotation(new Rectangle(35, 760, 160, 15)); PdfExplicitDestination destToPage3 = PdfExplicitDestination.CreateFit(document.GetPage(3)); String stringDest = "thirdPageDest"; document.AddNamedDestination(stringDest, destToPage3.GetPdfObject()); linkStringDest.SetAction(PdfAction.CreateGoTo(new PdfStringDestination(stringDest))); firstPage.AddAnnotation(linkStringDest); document.Close(); NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFile, cmpFile, destinationFolder, "diff_" )); }
private void ProcessAction(PdfAction pdfAction) { if (pdfAction.ActionType == ActionTypes.Uri) Process.Start(pdfAction.ActionUrl); else if (pdfAction.Destination != null) ProcessDestination(pdfAction.Destination); }