public void VerifyPageTextAndFontTest() { var file = new PdfFile(); var page = PdfPage.NewLetter(); var text = new PdfText("foo", new PdfFontType1(PdfFontType1Type.Helvetica), PdfMeasurement.Points(12.0), new PdfPoint(PdfMeasurement.Inches(1.0), PdfMeasurement.Inches(2.0))); page.Items.Add(text); file.Pages.Add(page); AssertFileContains(file, @" BT /F1 12.00 Tf 72.00 144.00 Td [(foo)] TJ ET "); AssertFileContains(file, @" /Resources <</Font <</F1 5 0 R>>>> "); AssertFileContains(file, "<</Type /Font /Subtype /Type1 /BaseFont /Helvetica>>"); text.CharacterWidth = PdfMeasurement.Points(0.25); AssertFileContains(file, @" BT /F1 12.00 Tf 72.00 144.00 Td 0.25 Tc [(foo)] TJ ET "); }
static void Main(string[] args) { //using (var doc = new PdfDocument("TestDoc.pdf", "password")) using (var doc = new PdfDocument(@"C:\Users\rafae\Downloads\EN-US-CNTNT-eBook-Build a Competitive Edge With SaaS Apps.pdf")) { int pageNumber = 0; foreach (var page in doc.Pages) { using (page) { using (var bitmap = new PDFiumBitmap((int)page.Width, (int)page.Height, true)) using (var stream = new FileStream($"{pageNumber}.bmp", FileMode.Create)) { page.Render(bitmap); bitmap.Save(stream); } using (var text = PdfText.Load(page)) { File.WriteAllText($"{pageNumber}.txt", text.GetText()); var parts = text.GetSegmentedText(); File.WriteAllLines($"{pageNumber}.bti.txt", parts.Select(ti => ti.Text)); } } pageNumber++; } } }
public void StringEscapeSequencesTest() { var page = PdfPage.NewLetter(); var text = new PdfText(@"outer (inner \backslash) after", new PdfFontType1(PdfFontType1Type.Helvetica), PdfMeasurement.Points(12.0), new PdfPoint()); page.Items.Add(text); AssertPageContains(page, @"[(outer \(inner \\backslash\) after)] TJ"); }
private void SetFooter(PdfDocumentControl htmlToPdfDocument) { // enable footer display htmlToPdfDocument.Footer.Enabled = true; // set footer height htmlToPdfDocument.Footer.Height = 50; // set footer background color htmlToPdfDocument.Footer.BackgroundColor = System.Drawing.Color.WhiteSmoke; float pdfPageWidth = htmlToPdfDocument.PageOrientation == PdfPageOrientation.Portrait ? htmlToPdfDocument.PageSize.Width : htmlToPdfDocument.PageSize.Height; float footerWidth = pdfPageWidth - htmlToPdfDocument.Margins.Left - htmlToPdfDocument.Margins.Right; float footerHeight = htmlToPdfDocument.Footer.Height; // layout HTML in footer PdfHtml footerHtml = new PdfHtml(5, 5, @"<span style=""color:Navy; font-family:Times New Roman; font-style:italic""> Quickly Create High Quality PDFs with </span><a href=""http://www.hiqpdf.com"">HiQPdf</a>", null); footerHtml.FitDestHeight = true; htmlToPdfDocument.Footer.Layout(footerHtml); if (m_formCollection["checkBoxDisplayPageNumbersInFooter"].Count > 0) { if (m_formCollection["checkBoxPageNumbersInHtml"].Count == 0) { // add page numbering in a text element System.Drawing.Font pageNumberingFont = new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 8, System.Drawing.GraphicsUnit.Point); PdfText pageNumberingText = new PdfText(5, footerHeight - 12, "Page {CrtPage} of {PageCount}", pageNumberingFont); pageNumberingText.HorizontalAlign = PdfTextHAlign.Center; pageNumberingText.EmbedSystemFont = true; pageNumberingText.ForeColor = System.Drawing.Color.DarkGreen; htmlToPdfDocument.Footer.Layout(pageNumberingText); } else { // add page numbers in HTML - more flexible but less efficient than text version PdfHtmlWithPlaceHolders htmlWithPageNumbers = new PdfHtmlWithPlaceHolders(5, footerHeight - 20, "Page <span style=\"font-size: 16px; color: blue; font-style: italic; font-weight: bold\">{CrtPage}</span> of <span style=\"font-size: 16px; color: green; font-weight: bold\">{PageCount}</span>", null); htmlToPdfDocument.Footer.Layout(htmlWithPageNumbers); } } string footerImageFile = m_hostingEnvironment.ContentRootPath + @"\wwwroot" + @"\DemoFiles\Images\HiQPdfLogo.png"; PdfImage logoFooterImage = new PdfImage(footerWidth - 40 - 5, 5, 40, System.Drawing.Image.FromFile(footerImageFile)); htmlToPdfDocument.Footer.Layout(logoFooterImage); // create a border for footer PdfRectangle borderRectangle = new PdfRectangle(1, 1, footerWidth - 2, footerHeight - 2); borderRectangle.LineStyle.LineWidth = 0.5f; borderRectangle.ForeColor = System.Drawing.Color.DarkGreen; htmlToPdfDocument.Footer.Layout(borderRectangle); }
public ActionResult CreatePdf(IFormCollection collection) { // create a PDF document PdfDocument document = new PdfDocument(); // set a demo serial number document.SerialNumber = "YCgJMTAE-BiwJAhIB-EhlWTlBA-UEBRQFBA-U1FOUVJO-WVlZWQ=="; // create a page in document PdfPage page1 = document.AddPage(); // create the true type fonts that can be used in document text Font sysFont = new Font("Times New Roman", 10, System.Drawing.GraphicsUnit.Point); PdfFont pdfFont = document.CreateFont(sysFont); PdfFont pdfFontEmbed = document.CreateFont(sysFont, true); float crtYPos = 20; float crtXPos = 5; // add a title to PDF document PdfText titleTextTransImage = new PdfText(crtXPos, crtYPos, "Click the image below to open the digital signature", pdfFontEmbed); titleTextTransImage.ForeColor = Color.Navy; PdfLayoutInfo textLayoutInfo = page1.Layout(titleTextTransImage); crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; // layout a PNG image with alpha transparency PdfImage transparentPdfImage = new PdfImage(crtXPos, crtYPos, m_hostingEnvironment.ContentRootPath + @"\wwwroot" + @"\DemoFiles\Images\HiQPdfLogo_small.png"); PdfLayoutInfo imageLayoutInfo = page1.Layout(transparentPdfImage); // apply a digital sgnature over the image PdfCertificatesCollection pdfCertificates = PdfCertificatesCollection.FromFile(m_hostingEnvironment.ContentRootPath + @"\wwwroot" + @"\DemoFiles\Pfx\hiqpdf.pfx", "hiqpdf"); PdfDigitalSignature digitalSignature = new PdfDigitalSignature(pdfCertificates[0]); digitalSignature.SigningReason = "My signing reason"; digitalSignature.SigningLocation = "My signing location"; digitalSignature.SignerContactInfo = "My contact info"; document.AddDigitalSignature(digitalSignature, imageLayoutInfo.LastPdfPage, imageLayoutInfo.LastPageRectangle); try { // write the PDF document to a memory buffer byte[] pdfBuffer = document.WriteToMemory(); FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf"); fileResult.FileDownloadName = "DigitalSignatures.pdf"; return(fileResult); } finally { document.Close(); } }
private void SetFooter(PdfDocumentControl htmlToPdfDocument) { // enable footer display htmlToPdfDocument.Footer.Enabled = checkBoxAddFooter.Checked; if (!htmlToPdfDocument.Footer.Enabled) { return; } // set footer height htmlToPdfDocument.Footer.Height = 50; // set footer background color htmlToPdfDocument.Footer.BackgroundColor = System.Drawing.Color.WhiteSmoke; float pdfPageWidth = htmlToPdfDocument.PageOrientation == PdfPageOrientation.Portrait ? htmlToPdfDocument.PageSize.Width : htmlToPdfDocument.PageSize.Height; float footerWidth = pdfPageWidth - htmlToPdfDocument.Margins.Left - htmlToPdfDocument.Margins.Right; float footerHeight = htmlToPdfDocument.Footer.Height; // layout HTML in footer PdfHtml footerHtml = new PdfHtml(5, 5, @"<span style=""color:Navy; font-family:Times New Roman; font-style:italic""> Quickly Create High Quality PDFs with </span><a href=""http://www.hiqpdf.com"">HiQPdf</a>", null); footerHtml.FitDestHeight = true; footerHtml.FontEmbedding = checkBoxFontEmbedding.Checked; htmlToPdfDocument.Footer.Layout(footerHtml); // add page numbering System.Drawing.Font pageNumberingFont = new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 8, System.Drawing.GraphicsUnit.Point); PdfText pageNumberingText = new PdfText(5, footerHeight - 12, "Page {CrtPage} of {PageCount}", pageNumberingFont); pageNumberingText.HorizontalAlign = PdfTextHAlign.Center; pageNumberingText.EmbedSystemFont = true; pageNumberingText.ForeColor = System.Drawing.Color.DarkGreen; htmlToPdfDocument.Footer.Layout(pageNumberingText); string footerImageFile = Server.MapPath("~") + @"\DemoFiles\Images\HiQPdfLogo.png"; PdfImage logoFooterImage = new PdfImage(footerWidth - 40 - 5, 5, 40, System.Drawing.Image.FromFile(footerImageFile)); htmlToPdfDocument.Footer.Layout(logoFooterImage); // create a border for footer PdfRectangle borderRectangle = new PdfRectangle(1, 1, footerWidth - 2, footerHeight - 2); borderRectangle.LineStyle.LineWidth = 0.5f; borderRectangle.ForeColor = System.Drawing.Color.DarkGreen; htmlToPdfDocument.Footer.Layout(borderRectangle); }
private static void _setFooter(PdfDocumentControl objPdf, string logoFooterPath, string objFooterHtml, bool enableRectangleFooterBorder, int footerHeight = 50) { if (objFooterHtml == null) { throw new ArgumentNullException("objFooterHtml"); } objPdf.Footer.Enabled = true; //if (!objPDF.Footer.Enabled) return; objPdf.Footer.Height = footerHeight; objPdf.Footer.BackgroundColor = Color.WhiteSmoke; var pdfPageWidth = objPdf.PageOrientation == PdfPageOrientation.Portrait ? objPdf.PageSize.Width : objPdf.PageSize.Height; var footerWidth = pdfPageWidth - objPdf.Margins.Left - objPdf.Margins.Right; var footerHtml = new PdfHtml(5, 5, objFooterHtml, null) { FitDestHeight = true }; objPdf.Footer.Layout(footerHtml); //footerHtml.FontEmbedding = enableFontEmbedding; var pageNumberingFont = new Font(new FontFamily("Times New Roman"), 8, GraphicsUnit.Point); var pageNumberingText = new PdfText(5, footerHeight - 12, "Page {CrtPage} of {PageCount}", pageNumberingFont) { HorizontalAlign = PdfTextHAlign.Right, EmbedSystemFont = true, ForeColor = Color.DarkGreen }; objPdf.Footer.Layout(pageNumberingText); if (logoFooterPath.Length > 5) { var logoFooterImage = new PdfImage(footerWidth - 40 - 5, 5, 40, Image.FromFile(logoFooterPath)); objPdf.Footer.Layout(logoFooterImage); } if (!enableRectangleFooterBorder) { return; } var borderRectangle = new PdfRectangle(1, 1, footerWidth - 2, footerHeight - 2) { LineStyle = { LineWidth = 0.5f }, ForeColor = Color.DarkGreen }; objPdf.Footer.Layout(borderRectangle); }
/// <summary> /// updates the html header based on html content /// </summary> /// <param name="pdfDocumentControl"></param> /// <param name="headerHtml"></param> /// <param name="baseUri"></param> /// <param name="templateOption"></param> private void SetHeader(PdfDocumentControl pdfDocumentControl, string headerHtml, string baseUri, TemplateOption templateOption = null) { PdfHtml headerPdfHtml = new PdfHtml(headerHtml, baseUri); pdfDocumentControl.Header.Enabled = true; float pdfPageWidth = 0, headerWidth = 0, headerHeight = 0; if (templateOption != null) { if (templateOption.HeaderHeight.HasValue) { pdfDocumentControl.Header.Height = templateOption.HeaderHeight.Value; } pdfPageWidth = pdfDocumentControl.PageOrientation == PdfPageOrientation.Portrait ? pdfDocumentControl.PageSize.Width : pdfDocumentControl.PageSize.Height; headerWidth = pdfPageWidth - pdfDocumentControl.Margins.Left - pdfDocumentControl.Margins.Right; headerHeight = pdfDocumentControl.Header.Height; PdfLine leftLine = new PdfLine(new System.Drawing.PointF(leftStartXPoint, 10), new System.Drawing.PointF(leftStartXPoint, headerHeight)); PdfLine rightLine = new PdfLine(new System.Drawing.PointF((float)(headerWidth - 2.5), 10), new System.Drawing.PointF((float)(headerWidth - 2.5), headerHeight)); PdfLine topLine = new PdfLine(new System.Drawing.PointF(leftStartXPoint, 10), new System.Drawing.PointF((float)(headerWidth - 2.5), 10)); //Border Color for the PDF if (!string.IsNullOrEmpty(templateOption.PageMargin.Color)) { leftLine.ForeColor = System.Drawing.Color.FromName(templateOption.PageMargin.Color); leftLine.BackColor = System.Drawing.Color.FromName(templateOption.PageMargin.Color); rightLine.ForeColor = System.Drawing.Color.FromName(templateOption.PageMargin.Color); rightLine.BackColor = System.Drawing.Color.FromName(templateOption.PageMargin.Color); topLine.ForeColor = System.Drawing.Color.FromName(templateOption.PageMargin.Color); topLine.BackColor = System.Drawing.Color.FromName(templateOption.PageMargin.Color); } pdfDocumentControl.Header.Layout(leftLine); pdfDocumentControl.Header.Layout(rightLine); pdfDocumentControl.Header.Layout(topLine); } // add page numbering in a text element System.Drawing.Font pageNumberingFont = new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 8, System.Drawing.GraphicsUnit.Point); PdfText pageNumberingText = new PdfText(headerWidth - 60, 0, "Page {CrtPage} of {PageCount}", pageNumberingFont); pageNumberingText.EmbedSystemFont = true; pdfDocumentControl.Header.Layout(pageNumberingText); pdfDocumentControl.Header.Layout(headerPdfHtml); }
public void VerifyFontsAreAddedOnSaveTest() { var file = new PdfFile(); var page = PdfPage.NewLetter(); var text = new PdfText("foo", new PdfFontType1(PdfFontType1Type.Helvetica), PdfMeasurement.Points(12.0), new PdfPoint()); page.Items.Add(text); file.Pages.Add(page); Assert.Equal(0, file.Fonts.Count); using (var ms = new MemoryStream()) { file.Save(ms); } Assert.True(ReferenceEquals(text.Font, file.Fonts.Single())); }
private void SetFooter(PdfDocument document) { if (m_formCollection["checkBoxAddFooter"].Count > 0) { return; } //create the document footer document.CreateFooterCanvas(50); // layout HTML in footer PdfHtml footerHtml = new PdfHtml(5, 5, @"<span style=""color:Navy; font-family:Times New Roman; font-style:italic""> Quickly Create High Quality PDFs with </span><a href=""http://www.hiqpdf.com"">HiQPdf</a>", null); footerHtml.FitDestHeight = true; footerHtml.FontEmbedding = true; document.Footer.Layout(footerHtml); float footerHeight = document.Footer.Height; float footerWidth = document.Footer.Width; // add page numbering System.Drawing.Font pageNumberingFont = new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 8, System.Drawing.GraphicsUnit.Point); PdfText pageNumberingText = new PdfText(5, footerHeight - 12, "Page {CrtPage} of {PageCount}", pageNumberingFont); pageNumberingText.HorizontalAlign = PdfTextHAlign.Center; pageNumberingText.EmbedSystemFont = true; pageNumberingText.ForeColor = System.Drawing.Color.DarkGreen; document.Footer.Layout(pageNumberingText); string footerImageFile = m_hostingEnvironment.ContentRootPath + @"\wwwroot" + @"\DemoFiles\Images\HiQPdfLogo.png"; PdfImage logoFooterImage = new PdfImage(footerWidth - 40 - 5, 5, 40, System.Drawing.Image.FromFile(footerImageFile)); document.Footer.Layout(logoFooterImage); // create a border for footer PdfRectangle borderRectangle = new PdfRectangle(1, 1, footerWidth - 2, footerHeight - 2); borderRectangle.LineStyle.LineWidth = 0.5f; borderRectangle.ForeColor = System.Drawing.Color.DarkGreen; document.Footer.Layout(borderRectangle); }
public void AddText(string text, int x, int y) { PdfFont font = new PdfFont(ObjectNumber, "Times-Roman"); PdfObjects.Add(font); ObjectNumber++; PdfObject procSet = new PdfObject(ObjectNumber); procSet.Dictionary.Add("ProcSet", $"[/PDF /Text]"); procSet.Dictionary.Add("Font", $"<< {font.Name} {font.PdfReference()} >>"); PdfObjects.Add(procSet); ObjectNumber++; PdfText textObj = new PdfText(ObjectNumber, text, x, y, CurrentPage.MediaBox); CurrentPage.AddContent(textObj); PdfObjects.Add(textObj); ObjectNumber++; }
public void VerifyStreamFilterTest() { var page = new PdfPage(PdfMeasurement.Inches(8.5), PdfMeasurement.Inches(11.0), new ASCIIHexEncoder()); var text = new PdfText("foo", new PdfFontType1(PdfFontType1Type.Helvetica), PdfMeasurement.Points(12.0), new PdfPoint(PdfMeasurement.Inches(1.0), PdfMeasurement.Inches(1.0))); page.Items.Add(text); var expected = @" <</Length 185 /Filter [/ASCIIHexDecode] >> stream 3020770D0A30203020302052470D0A30203020302072670D0A42540D0A202020202F46312031322E30302054660D0A2020202037322E30302037322E30302054 640D0A202020205B28666F6F295D20544A0D0A45540D0A530D0A> endstream endobj "; AssertPageContains(page, expected); }
private void SetFooter(PdfDocumentControl htmlToPdfDocument, string fileType = "PriceList") { // enable footer display htmlToPdfDocument.Footer.Enabled = true; // set footer height htmlToPdfDocument.Footer.Height = 45; // set footer background color //htmlToPdfDocument.Footer.BackgroundColor = System.Drawing.Color.WhiteSmoke; float pdfPageWidth = htmlToPdfDocument.PageOrientation == PdfPageOrientation.Portrait ? htmlToPdfDocument.PageSize.Width : htmlToPdfDocument.PageSize.Height; float footerWidth = pdfPageWidth - htmlToPdfDocument.Margins.Left - htmlToPdfDocument.Margins.Right; float footerHeight = htmlToPdfDocument.Footer.Height; Font pageNumberingFont = new Font(new System.Drawing.FontFamily("Verdana"), 8, System.Drawing.GraphicsUnit.Point); if (fileType == "PHStudyReport") { htmlToPdfDocument.Footer.Layout(new PdfHtml(0, 10, "<a href=\"http://www.discoverx.com\" style=\"font-family:Arial; font-size:16px; color:black; text-decoration:none\">http://www.discoverx.com</a>", null)); } else { string logoImageFile = HttpContext.Current.Server.MapPath(Utility.GetAPPSettingKey("ImageFolder") + "PDFCover/DRx_logo_2013.png"); PdfImage logoImage = new PdfImage(5, 5, 40, Image.FromFile(logoImageFile)); htmlToPdfDocument.Footer.Layout(logoImage); htmlToPdfDocument.Footer.Layout(new PdfHtml(0, 10, "<a href=\"http://www.discoverx.com\" style=\"font-family:Verdana; font-size:9px; color:black; text-decoration:none\">http://www.discoverx.com</a>", null)); } string footerStr = string.Empty; if (fileType == "PriceList") { footerStr = PRICE_LIST_FOOTER; } else if (fileType == "TargetList") { footerStr = TARGET_LIST_FOOTER; } else if (fileType == "PHStudyReport") { footerStr = PHSTUDY_REPORT_FOOTER; } // layout HTML in footer //footerHtml.FitDestHeight = true; PdfText centerText = new PdfText(5, 10, footerStr, pageNumberingFont); centerText.HorizontalAlign = PdfTextHAlign.Center; centerText.EmbedSystemFont = true; centerText.ForeColor = System.Drawing.Color.Black; htmlToPdfDocument.Footer.Layout(centerText); //htmlToPdfDocument.Footer.Layout(new PdfHtml(200, 5, footerStr, null)); PdfText rightText; if (fileType == "PHStudyReport") { rightText = new PdfText(5, 10, string.Format("{0}", DateTime.Now.ToShortDateString()), pageNumberingFont); } else { rightText = new PdfText(5, 10, string.Format("Q{0} - {1}", DateTime.Now.GetQuarter(), DateTime.Now.Year), pageNumberingFont); } rightText.HorizontalAlign = PdfTextHAlign.Right; rightText.EmbedSystemFont = true; rightText.ForeColor = System.Drawing.Color.Black; htmlToPdfDocument.Footer.Layout(rightText); //htmlToPdfDocument.Footer.Layout(new PdfHtml(500, 5, 80, 6, footerStr, null)); // add page numbering in a text element PdfText pageNumberingText = new PdfText(5, footerHeight - 25, "{CrtPage}", pageNumberingFont); pageNumberingText.HorizontalAlign = PdfTextHAlign.Center; pageNumberingText.EmbedSystemFont = true; pageNumberingText.ForeColor = System.Drawing.Color.Black; htmlToPdfDocument.Footer.Layout(pageNumberingText); /* * string footerImageFile = Server.MapPath("~") + @"\DemoFiles\Images\HiQPdfLogo.png"; * PdfImage logoFooterImage = new PdfImage(footerWidth - 40 - 5, 5, 40, * System.Drawing.Image.FromFile(footerImageFile)); * htmlToPdfDocument.Footer.Layout(logoFooterImage); */ /* * // create a border for footer * PdfRectangle borderRectangle = new PdfRectangle(1, 1, footerWidth - 2, footerHeight - 2); * borderRectangle.LineStyle.LineWidth = 0.5f; * borderRectangle.ForeColor = System.Drawing.Color.DarkGreen; * htmlToPdfDocument.Footer.Layout(borderRectangle); */ }
public ActionResult CreatePdf(FormCollection collection) { // create a PDF document PdfDocument document = new PdfDocument(); // set a demo serial number document.SerialNumber = "YCgJMTAE-BiwJAhIB-EhlWTlBA-UEBRQFBA-U1FOUVJO-WVlZWQ=="; // create the true type fonts that can be used in document System.Drawing.Font ttfFont = new System.Drawing.Font("Times New Roman", 10, System.Drawing.GraphicsUnit.Point); PdfFont newTimesFont = document.CreateFont(ttfFont); PdfFont newTimesFontEmbed = document.CreateFont(ttfFont, true); // create page 1 PdfPage page1 = document.AddPage(); // create a text object to be laid out on this page PdfText text1 = new PdfText(10, 10, "This is the Page 1 of the document with Open action", newTimesFontEmbed); // layout the text page1.Layout(text1); // create page 2 PdfPage page2 = document.AddPage(); // create a text object to be laid out on this page PdfText text2 = new PdfText(10, 10, "This is the Page 2 of the document with Open action", newTimesFontEmbed); // layout the text page2.Layout(text2); // create page 1 PdfPage page3 = document.AddPage(); // create a text object to be laid out on this page PdfText text3 = new PdfText(10, 10, "This is the Page 3 of the document with Open action", newTimesFontEmbed); // layout the text page3.Layout(text3); if (collection["ActionType"] == "radioButtonJavaScript") { // display an alert message when the document is opened string alertMessage = collection["textBoxAlertMessage"]; string javaScriptCode = "app.alert({cMsg: \"" + alertMessage + "\", cTitle: \"Open Document JavaScript Action\"});"; // create the JavaScript action to display the alert PdfJavaScriptAction javaScriptAction = new PdfJavaScriptAction(javaScriptCode); // set the document JavaScript open action document.SetOpenAction(javaScriptAction); } else { // go to a given page in document and set the given zoom level when the document is opened int pageIndex = collection["PageNumber"] == "radioButtonPage1" ? 0 : (collection["PageNumber"] == "radioButtonPage2" ? 1 : 2); int zoomLevel = int.Parse(collection["textBoxZoomLevel"]); PdfDestination openDestination = new PdfDestination(document.Pages[pageIndex], new System.Drawing.PointF(10, 10)); openDestination.Zoom = zoomLevel; PdfGoToAction goToAction = new PdfGoToAction(openDestination); // set the document GoTo open action document.SetOpenAction(goToAction); } try { // write the PDF document to a memory buffer byte[] pdfBuffer = document.WriteToMemory(); FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf"); fileResult.FileDownloadName = "OpenAction.pdf"; return(fileResult); } finally { document.Close(); } }
/// <summary> /// Representación textual de esta /// instancia de PdfUnstructuredPage. /// </summary> /// <returns>Representación textual de la instancia.</returns> public override string ToString() { return($"{PdfText.Substring(0, 70)}..."); }
public ActionResult CreatePdf(FormCollection collection) { // create a PDF document PdfDocument document = new PdfDocument(); // set a demo serial number document.SerialNumber = "YCgJMTAE-BiwJAhIB-EhlWTlBA-UEBRQFBA-U1FOUVJO-WVlZWQ=="; // display the attachments when the document is opened document.Viewer.PageMode = PdfPageMode.Attachments; // create a page in document PdfPage page1 = document.AddPage(); // 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); // 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 an attachment with icon from file string filePath1 = Server.MapPath("~") + @"\DemoFiles\Attach\TextAttach1.txt"; PdfAttachment pdfAttachment1 = document.CreateAttachmentFromFile(page1, new System.Drawing.RectangleF(10, 30, 10, 20), PdfAttachIconType.PushPin, filePath1); pdfAttachment1.Description = "Attachment with icon from a file"; // write a description at the right of the icon PdfText pdfAttachment1Descr = new PdfText(40, 35, pdfAttachment1.Description, pdfFontEmbed); page1.Layout(pdfAttachment1Descr); // create an attachment with icon from a stream // The stream must remain opened until the document is saved System.IO.FileStream fileStream2 = new System.IO.FileStream(filePath1, System.IO.FileMode.Open, System.IO.FileAccess.Read); PdfAttachment pdfAttachment2 = document.CreateAttachmentFromStream(page1, new System.Drawing.RectangleF(10, 60, 10, 20), PdfAttachIconType.Paperclip, fileStream2, "AttachFromStream_WithIcon.txt"); pdfAttachment2.Description = "Attachment with icon from a stream"; // write a description at the right of the icon PdfText pdfAttachment2Descr = new PdfText(40, 65, pdfAttachment2.Description, pdfFontEmbed); page1.Layout(pdfAttachment2Descr); // create an attachment without icon in PDF from a file string filePath2 = Server.MapPath("~") + @"\DemoFiles\Attach\TextAttach2.txt"; document.CreateAttachmentFromFile(filePath2); // create an attachment without icon in PDF from a stream // The stream must remain opened until the document is saved System.IO.FileStream fileStream1 = new System.IO.FileStream(filePath2, System.IO.FileMode.Open, System.IO.FileAccess.Read); document.CreateAttachmentFromStream(fileStream1, "AttachFromStream_NoIcon.txt"); // dispose the graphics used for measuring refGraphics.Dispose(); refBmp.Dispose(); try { // write the PDF document to a memory buffer byte[] pdfBuffer = document.WriteToMemory(); FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf"); fileResult.FileDownloadName = "PdfAttachments.pdf"; return(fileResult); } finally { document.Close(); fileStream1.Close(); } }
public ActionResult CreatePdf(IFormCollection collection) { // create a PDF document PdfDocument document = new PdfDocument(); // set a demo serial number document.SerialNumber = "YCgJMTAE-BiwJAhIB-EhlWTlBA-UEBRQFBA-U1FOUVJO-WVlZWQ=="; // create a page in document PdfPage page1 = document.AddPage(); // set a background color for the page PdfRectangle backgroundRectangle = new PdfRectangle(page1.DrawableRectangle); backgroundRectangle.BackColor = System.Drawing.Color.WhiteSmoke; page1.Layout(backgroundRectangle); // create the true type fonts that can be used in document text 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); float crtYPos = 20; float crtXPos = 5; #region Layout transparent image PdfText titleTextTransImage = new PdfText(crtXPos, crtYPos, "PNG image with alpha transparency:", pdfFontEmbed); titleTextTransImage.ForeColor = System.Drawing.Color.Navy; PdfLayoutInfo textLayoutInfo = page1.Layout(titleTextTransImage); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; // layout a PNG image with alpha transparency PdfImage transparentPdfImage = new PdfImage(crtXPos, crtYPos, m_hostingEnvironment.ContentRootPath + @"\wwwroot" + @"\DemoFiles\Images\HiQPdfLogo_small.png"); PdfLayoutInfo imageLayoutInfo = page1.Layout(transparentPdfImage); // advance the Y position in the PDF page crtYPos += imageLayoutInfo.LastPageRectangle.Height + 10; #endregion #region Layout resized transparent image PdfText titleTextTransImageResized = new PdfText(crtXPos, crtYPos, "The transparent PNG image below is resized:", pdfFontEmbed); titleTextTransImageResized.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTextTransImageResized); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; // layout a PNG image with alpha transparency PdfImage transparentResizedPdfImage = new PdfImage(crtXPos, crtYPos, 50, m_hostingEnvironment.ContentRootPath + @"\wwwroot" + @"\DemoFiles\Images\HiQPdfLogo_small.png"); imageLayoutInfo = page1.Layout(transparentResizedPdfImage); // advance the Y position in the PDF page crtYPos += imageLayoutInfo.LastPageRectangle.Height + 10; #endregion #region Layout rotated transparent image PdfText titleTextTransImageRotated = new PdfText(crtXPos, crtYPos, "The transparent PNG image below is rotated 180 degrees counter clockwise:", pdfFontEmbed); titleTextTransImageRotated.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTextTransImageRotated); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; // rotate the PNG image with alpha transparency 180 degrees counter clockwise PdfImage transparentRotatedPdfImage = new PdfImage(0, 0, 50, m_hostingEnvironment.ContentRootPath + @"\wwwroot" + @"\DemoFiles\Images\HiQPdfLogo_small.png"); // translate the coordinates system to image location transparentRotatedPdfImage.SetTranslation(crtXPos, crtYPos); // rotate the coordinates system counter clockwise transparentRotatedPdfImage.SetRotationAngle(180); // translate back the coordinates system transparentRotatedPdfImage.SetTranslation(-50, -50); imageLayoutInfo = page1.Layout(transparentRotatedPdfImage); // advance the Y position in the PDF page crtYPos += 50 + 10; #endregion #region Layout clipped transparent image PdfText titleTextTransClippedImage = new PdfText(crtXPos, crtYPos, "The transparent PNG image below is clipped:", pdfFontEmbed); titleTextTransClippedImage.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTextTransClippedImage); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; // layout a clipped PNG image with alpha transparency PdfImage transparentClippedPdfImage = new PdfImage(crtXPos, crtYPos, 50, m_hostingEnvironment.ContentRootPath + @"\wwwroot" + @"\DemoFiles\Images\HiQPdfLogo_small.png"); transparentClippedPdfImage.ClipRectangle = new System.Drawing.RectangleF(crtXPos, crtYPos, 50, 25); imageLayoutInfo = page1.Layout(transparentClippedPdfImage); // advance the Y position in the PDF page crtYPos += transparentClippedPdfImage.ClipRectangle.Height + 10; #endregion #region Layout JPEG image PdfText titleTextOpaqueImage = new PdfText(crtXPos, crtYPos, "The JPG image below is opaque:", pdfFontEmbed); titleTextOpaqueImage.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTextOpaqueImage); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; // layout an opaque JPG image PdfImage opaquePdfImage = new PdfImage(crtXPos, crtYPos, m_hostingEnvironment.ContentRootPath + @"\wwwroot" + @"\DemoFiles\Images\HiQPdfLogo_small.jpg"); imageLayoutInfo = page1.Layout(opaquePdfImage); // advance the Y position in the PDF page crtYPos += imageLayoutInfo.LastPageRectangle.Height + 10; #endregion #region Layout clipped JPEG image PdfText titleTextClippedImage = new PdfText(crtXPos, crtYPos, "The JPG image below is clipped:", pdfFontEmbed); titleTextClippedImage.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTextClippedImage); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; // layout a clipped image PdfImage clippedPdfImage = new PdfImage(crtXPos, crtYPos, 50, m_hostingEnvironment.ContentRootPath + @"\wwwroot" + @"\DemoFiles\Images\HiQPdfLogo_small.jpg"); clippedPdfImage.ClipRectangle = new System.Drawing.RectangleF(crtXPos, crtYPos, 50, 25); imageLayoutInfo = page1.Layout(clippedPdfImage); // advance the Y position in the PDF page crtYPos += clippedPdfImage.ClipRectangle.Height + 10; #endregion #region Layout a vectorial SVG image PdfText titleTextSvgImage = new PdfText(crtXPos, crtYPos, "Vectorial SVG image:", pdfFontEmbed); titleTextSvgImage.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTextSvgImage); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; string svgImageCode = System.IO.File.ReadAllText(m_hostingEnvironment.ContentRootPath + @"\wwwroot" + @"\DemoFiles\Svg\SvgImage.svg"); PdfHtml svgImage = new PdfHtml(crtXPos, crtYPos, svgImageCode, null); PdfLayoutInfo svgLayoutInfo = page1.Layout(svgImage); // advance the Y position in the PDF page crtYPos += svgImage.ConversionInfo.PdfRegions[0].Rectangle.Height + 10; #endregion #region Layout JPEG image on multiple pages PdfText titleTexMultiPageImage = new PdfText(crtXPos, crtYPos, "The JPG image below is laid out on 2 pages:", pdfFontEmbed); titleTexMultiPageImage.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTexMultiPageImage); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; // layout an opaque JPG image on 2 pages PdfImage paginatedPdfImage = new PdfImage(crtXPos, crtYPos, m_hostingEnvironment.ContentRootPath + @"\wwwroot" + @"\DemoFiles\Images\HiQPdfLogo_big.jpg"); imageLayoutInfo = page1.Layout(paginatedPdfImage); #endregion // get the last page PdfPage crtPage = document.Pages[imageLayoutInfo.LastPageIndex]; crtYPos = imageLayoutInfo.LastPageRectangle.Bottom + 10; #region Layout the screenshot of a HTML document PdfText titleTextHtmlImage = new PdfText(crtXPos, crtYPos, "HTML document screenshot:", pdfFontEmbed); titleTextHtmlImage.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = crtPage.Layout(titleTextHtmlImage); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; string htmlFile = m_hostingEnvironment.ContentRootPath + @"\wwwroot" + @"\DemoFiles\Html\Logo.Html"; PdfHtmlImage htmlRasterImage = new PdfHtmlImage(crtXPos, crtYPos, htmlFile); htmlRasterImage.BrowserWidth = 400; PdfLayoutInfo htmlLayoutInfo = crtPage.Layout(htmlRasterImage); // advance the Y position in the PDF page crtYPos += htmlRasterImage.ConversionInfo.PdfRegions[0].Rectangle.Height + 10; #endregion try { // write the PDF document to a memory buffer byte[] pdfBuffer = document.WriteToMemory(); FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf"); fileResult.FileDownloadName = "PdfImages.pdf"; return(fileResult); } finally { document.Close(); } }
private void SetFooter(PdfDocumentControl htmlToPdfDocument) { // enable footer display htmlToPdfDocument.Footer.Enabled = true; // set footer height htmlToPdfDocument.Footer.Height = 15; // set footer background color htmlToPdfDocument.Footer.BackgroundColor = System.Drawing.Color.WhiteSmoke; float pdfPageWidth = htmlToPdfDocument.PageOrientation == PdfPageOrientation.Portrait ? htmlToPdfDocument.PageSize.Width : htmlToPdfDocument.PageSize.Height; float footerWidth = pdfPageWidth - htmlToPdfDocument.Margins.Left - htmlToPdfDocument.Margins.Right; float footerHeight = htmlToPdfDocument.Footer.Height; // layout HTML in footer if (String.IsNullOrEmpty(TituloSistema)) TituloSistema = ""; if (String.IsNullOrEmpty(PiePagina)) PiePagina = "{0} {1} {2}"; if (String.IsNullOrEmpty(NombreCompleto)) NombreCompleto = ""; PdfHtml footerHtml = new PdfHtml(5, 0, String.Format(PiePagina, TituloSistema, NombreCompleto, DateTime.Now), null); footerHtml.FitDestHeight = true; htmlToPdfDocument.Footer.Layout(footerHtml); // add page numbering System.Drawing.Font pageNumberingFont = new System.Drawing.Font( new System.Drawing.FontFamily("Times New Roman"), 7, System.Drawing.GraphicsUnit.Point); PdfText pageNumberingText = new PdfText(footerWidth - 100, 6, "Página {CrtPage} de {PageCount}", pageNumberingFont); pageNumberingText.HorizontalAlign = PdfTextHAlign.Center; pageNumberingText.EmbedSystemFont = true; pageNumberingText.ForeColor = System.Drawing.Color.Gray; htmlToPdfDocument.Footer.Layout(pageNumberingText); }
public async Task <IActionResult> Upload(IFormFile file) { try { _log.LogDebug($"UploadFile file={file}"); string fileExtension = Path.GetExtension(file.FileName).Trim('.'); if (file == null || file.Length == 0) { throw new Exception("Файл не может быть пуст"); } if (CheckFileExtension.GetFileExtension(fileExtension) == FileExtension.Extensions.Unknown) { throw new Exception("Неподдерживаемый тип файла"); } string currentSid = Utils.GetSid(HttpContext); Document document = new Document(); PdfText text = null; ProcessResponse result; string dirPdfPath = Folder.GetAllPath(Path.Combine(Umk.IO.Folder.UploadsFolder, "pdf")); string filePdfPath = Path.Combine(dirPdfPath, $"{Path.GetFileNameWithoutExtension(file.FileName)}.pdf"); if (CheckFileExtension.GetFileExtension(fileExtension) == FileExtension.Extensions.Pdf) { result = await SendToPdfService(file); string documentId = Guid.NewGuid().ToString(); foreach (var infoPdf in result.Values) { document = new Document { doc_id = documentId, parent_id = null, path = filePdfPath.Substring(filePdfPath.IndexOf("\\uploads") + 1), type = Convert.ToByte(CheckFileExtension.GetFileExtension("pdf")), upload_time_stamp = DateTime.Now, short_name = Path.GetFileNameWithoutExtension(filePdfPath), user_sid = currentSid, picture = "data:image/jpg;base64," + Convert.ToBase64String(infoPdf.Image) }; _fileService.Add(document, file, filePdfPath, (f, ff) => { using (var pdfFileStream = new FileStream(filePdfPath, FileMode.Create)) { file.CopyTo(pdfFileStream); } }); foreach (var pdfText in infoPdf.TextValues) { text = new PdfText { parent_id = documentId, page_number = pdfText.Key, page_text = pdfText.Value, short_name = document.short_name }; } } } else { string dir = Folder.GetAllPath(Path.Combine(Umk.IO.Folder.UploadsFolder, fileExtension)); string filePath = Path.Combine(dir, file.FileName); string documentId = Guid.NewGuid().ToString(); document = new Models.Document { doc_id = documentId, parent_id = null, path = filePath.Substring(filePath.IndexOf("\\uploads") + 1), type = Convert.ToByte(CheckFileExtension.GetFileExtension(fileExtension)), upload_time_stamp = DateTime.Now, short_name = Path.GetFileNameWithoutExtension(filePath), user_sid = currentSid, picture = null }; _fileService.Add(document, file, filePath, (f, ff) => { using (var fileStream = new FileStream(filePath, FileMode.Create)) { file.CopyTo(fileStream); } }); result = await SendToPdfService(file); foreach (var infoPdf in result.Values) { document = new Models.Document { doc_id = Guid.NewGuid().ToString(), parent_id = documentId, path = filePdfPath.Substring(filePdfPath.IndexOf("\\uploads") + 1), type = Convert.ToByte(CheckFileExtension.GetFileExtension("pdf")), upload_time_stamp = DateTime.Now, short_name = Path.GetFileNameWithoutExtension(filePdfPath), user_sid = currentSid, picture = "data:image/jpg;base64," + Convert.ToBase64String(infoPdf.Image) }; _fileService.Add(document, file, filePdfPath, (f, ff) => { using (var pdfFileStream = new FileStream(filePdfPath, FileMode.Create)) using (Stream streamPdf = new MemoryStream(infoPdf.Pdf)) { streamPdf.CopyTo(pdfFileStream); } }); foreach (var pdfText in infoPdf.TextValues) { text = new PdfText { parent_id = documentId, page_number = pdfText.Key, page_text = pdfText.Value, short_name = document.short_name }; } } } _log.LogDebug("UploadDownloadController.Upload() OK"); return(Ok(document)); } catch (Exception e) { _log.LogError(e.Message); return(BadRequest(e.Message)); } }
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=="; // create a page in document PdfPage page1 = document.AddPage(); // set a background color for the page PdfRectangle backgroundRectangle = new PdfRectangle(page1.DrawableRectangle); backgroundRectangle.BackColor = System.Drawing.Color.WhiteSmoke; page1.Layout(backgroundRectangle); // create the true type fonts that can be used in document text 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); float crtYPos = 20; float crtXPos = 5; #region Layout transparent image PdfText titleTextTransImage = new PdfText(crtXPos, crtYPos, "PNG image with alpha transparency:", pdfFontEmbed); titleTextTransImage.ForeColor = System.Drawing.Color.Navy; PdfLayoutInfo textLayoutInfo = page1.Layout(titleTextTransImage); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; // layout a PNG image with alpha transparency PdfImage transparentPdfImage = new PdfImage(crtXPos, crtYPos, Server.MapPath("~") + @"\DemoFiles\Images\HiQPdfLogo_small.png"); PdfLayoutInfo imageLayoutInfo = page1.Layout(transparentPdfImage); // advance the Y position in the PDF page crtYPos += imageLayoutInfo.LastPageRectangle.Height + 10; #endregion #region Layout resized transparent image PdfText titleTextTransImageResized = new PdfText(crtXPos, crtYPos, "The transparent PNG image below is resized:", pdfFontEmbed); titleTextTransImageResized.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTextTransImageResized); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; // layout a PNG image with alpha transparency PdfImage transparentResizedPdfImage = new PdfImage(crtXPos, crtYPos, 50, Server.MapPath("~") + @"\DemoFiles\Images\HiQPdfLogo_small.png"); imageLayoutInfo = page1.Layout(transparentResizedPdfImage); // advance the Y position in the PDF page crtYPos += imageLayoutInfo.LastPageRectangle.Height + 10; #endregion #region Layout rotated transparent image PdfText titleTextTransImageRotated = new PdfText(crtXPos, crtYPos, "The transparent PNG image below is rotated 180 degrees counter clockwise:", pdfFontEmbed); titleTextTransImageRotated.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTextTransImageRotated); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; // rotate the PNG image with alpha transparency 180 degrees counter clockwise PdfImage transparentRotatedPdfImage = new PdfImage(0, 0, 50, Server.MapPath("~") + @"\DemoFiles\Images\HiQPdfLogo_small.png"); // translate the coordinates system to image location transparentRotatedPdfImage.SetTranslation(crtXPos, crtYPos); // rotate the coordinates system counter clockwise transparentRotatedPdfImage.SetRotationAngle(180); // translate back the coordinates system transparentRotatedPdfImage.SetTranslation(-50, -50); imageLayoutInfo = page1.Layout(transparentRotatedPdfImage); // advance the Y position in the PDF page crtYPos += 50 + 10; #endregion #region Layout clipped transparent image PdfText titleTextTransClippedImage = new PdfText(crtXPos, crtYPos, "The transparent PNG image below is clipped:", pdfFontEmbed); titleTextTransClippedImage.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTextTransClippedImage); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; // layout a clipped PNG image with alpha transparency PdfImage transparentClippedPdfImage = new PdfImage(crtXPos, crtYPos, 50, Server.MapPath("~") + @"\DemoFiles\Images\HiQPdfLogo_small.png"); transparentClippedPdfImage.ClipRectangle = new System.Drawing.RectangleF(crtXPos, crtYPos, 50, 25); imageLayoutInfo = page1.Layout(transparentClippedPdfImage); // advance the Y position in the PDF page crtYPos += transparentClippedPdfImage.ClipRectangle.Height + 10; #endregion #region Layout JPEG image PdfText titleTextOpaqueImage = new PdfText(crtXPos, crtYPos, "The JPG image below is opaque:", pdfFontEmbed); titleTextOpaqueImage.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTextOpaqueImage); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; // layout an opaque JPG image PdfImage opaquePdfImage = new PdfImage(crtXPos, crtYPos, Server.MapPath("~") + @"\DemoFiles\Images\HiQPdfLogo_small.jpg"); imageLayoutInfo = page1.Layout(opaquePdfImage); // advance the Y position in the PDF page crtYPos += imageLayoutInfo.LastPageRectangle.Height + 10; #endregion #region Layout clipped JPEG image PdfText titleTextClippedImage = new PdfText(crtXPos, crtYPos, "The JPG image below is clipped:", pdfFontEmbed); titleTextClippedImage.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTextClippedImage); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; // layout a clipped image PdfImage clippedPdfImage = new PdfImage(crtXPos, crtYPos, 50, Server.MapPath("~") + @"\DemoFiles\Images\HiQPdfLogo_small.jpg"); clippedPdfImage.ClipRectangle = new System.Drawing.RectangleF(crtXPos, crtYPos, 50, 25); imageLayoutInfo = page1.Layout(clippedPdfImage); // advance the Y position in the PDF page crtYPos += clippedPdfImage.ClipRectangle.Height + 10; #endregion #region Layout a vectorial SVG image PdfText titleTextSvgImage = new PdfText(crtXPos, crtYPos, "Vectorial SVG image:", pdfFontEmbed); titleTextSvgImage.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTextSvgImage); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; string svgImageCode = System.IO.File.ReadAllText(Server.MapPath("~") + @"\DemoFiles\Svg\SvgImage.svg"); PdfHtml svgImage = new PdfHtml(crtXPos, crtYPos, svgImageCode, null); PdfLayoutInfo svgLayoutInfo = page1.Layout(svgImage); // advance the Y position in the PDF page crtYPos += svgImage.ConversionInfo.PdfRegions[0].Rectangle.Height + 10; #endregion #region Layout JPEG image on multiple pages PdfText titleTexMultiPageImage = new PdfText(crtXPos, crtYPos, "The JPG image below is laid out on 2 pages:", pdfFontEmbed); titleTexMultiPageImage.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTexMultiPageImage); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; // layout an opaque JPG image on 2 pages PdfImage paginatedPdfImage = new PdfImage(crtXPos, crtYPos, Server.MapPath("~") + @"\DemoFiles\Images\HiQPdfLogo_big.jpg"); imageLayoutInfo = page1.Layout(paginatedPdfImage); #endregion // get the last page PdfPage crtPage = document.Pages[imageLayoutInfo.LastPageIndex]; crtYPos = imageLayoutInfo.LastPageRectangle.Bottom + 10; #region Layout the screenshot of a HTML document PdfText titleTextHtmlImage = new PdfText(crtXPos, crtYPos, "HTML document screenshot:", pdfFontEmbed); titleTextHtmlImage.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = crtPage.Layout(titleTextHtmlImage); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; string htmlFile = Server.MapPath("~") + @"\DemoFiles\Html\Logo.Html"; PdfHtmlImage htmlRasterImage = new PdfHtmlImage(crtXPos, crtYPos, htmlFile); htmlRasterImage.BrowserWidth = 400; PdfLayoutInfo htmlLayoutInfo = crtPage.Layout(htmlRasterImage); // advance the Y position in the PDF page crtYPos += htmlRasterImage.ConversionInfo.PdfRegions[0].Rectangle.Height + 10; #endregion 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=PdfImages.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(); } }
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=="; // create a page in document PdfPage page1 = document.AddPage(); // create the true type fonts that can be used in document text Font sysFont = new Font("Times New Roman", 10, System.Drawing.GraphicsUnit.Point); PdfFont pdfFont = document.CreateFont(sysFont); PdfFont pdfFontEmbed = document.CreateFont(sysFont, true); float crtYPos = 20; float crtXPos = 5; // add a title to PDF document PdfText titleTextTransImage = new PdfText(crtXPos, crtYPos, "Click the image below to open the digital signature", pdfFontEmbed); titleTextTransImage.ForeColor = Color.Navy; PdfLayoutInfo textLayoutInfo = page1.Layout(titleTextTransImage); crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; // layout a PNG image with alpha transparency PdfImage transparentPdfImage = new PdfImage(crtXPos, crtYPos, Server.MapPath("~") + @"\DemoFiles\Images\HiQPdfLogo_small.png"); PdfLayoutInfo imageLayoutInfo = page1.Layout(transparentPdfImage); // apply a digital sgnature over the image PdfCertificatesCollection pdfCertificates = PdfCertificatesCollection.FromFile(Server.MapPath("~") + @"\DemoFiles\Pfx\hiqpdf.pfx", "hiqpdf"); PdfDigitalSignature digitalSignature = new PdfDigitalSignature(pdfCertificates[0]); digitalSignature.SigningReason = "My signing reason"; digitalSignature.SigningLocation = "My signing location"; digitalSignature.SignerContactInfo = "My contact info"; document.AddDigitalSignature(digitalSignature, imageLayoutInfo.LastPdfPage, imageLayoutInfo.LastPageRectangle); 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=DigitalSignatures.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(); } }
public ActionResult CreatePdf(IFormCollection collection) { // create a PDF document PdfDocument document = new PdfDocument(); // set a demo serial number document.SerialNumber = "YCgJMTAE-BiwJAhIB-EhlWTlBA-UEBRQFBA-U1FOUVJO-WVlZWQ=="; // create a page in document PdfPage page1 = document.AddPage(); // create the true type fonts that can be used in document text 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", 10, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); PdfFont pdfFontBold = document.CreateFont(sysFontBold); PdfFont pdfFontBoldEmbed = document.CreateFont(sysFontBold, true); // create a standard Helvetica Type 1 font that can be used in document text PdfFont helveticaStdFont = document.CreateStandardFont(PdfStandardFont.Helvetica); helveticaStdFont.Size = 10; float crtYPos = 20; float crtXPos = 5; PdfLayoutInfo textLayoutInfo = null; string dummyText = @"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; #region Layout a text that expands to the right edge of the PDF page PdfText titleTextAtLocation = new PdfText(crtXPos, crtYPos, "The text below extends from the layout position to the right edge of the PDF page:", pdfFontBoldEmbed); titleTextAtLocation.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTextAtLocation); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; PdfText textExpandsToRightEdge = new PdfText(crtXPos + 50, crtYPos, dummyText, pdfFont); textExpandsToRightEdge.BackColor = System.Drawing.Color.WhiteSmoke; textLayoutInfo = page1.Layout(textExpandsToRightEdge); // draw a rectangle around the text PdfRectangle borderPdfRectangle = new PdfRectangle(textLayoutInfo.LastPageRectangle); borderPdfRectangle.LineStyle.LineWidth = 0.5f; page1.Layout(borderPdfRectangle); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; #endregion #region Layout a text with width limit PdfText titleTextWithWidth = new PdfText(crtXPos, crtYPos, "The text below is limited by a given width and has a free height:", pdfFontBoldEmbed); titleTextWithWidth.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTextWithWidth); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; PdfText textWithWidthLimit = new PdfText(crtXPos + 50, crtYPos, 300, dummyText, pdfFont); textWithWidthLimit.BackColor = System.Drawing.Color.WhiteSmoke; textLayoutInfo = page1.Layout(textWithWidthLimit); // draw a rectangle around the text borderPdfRectangle = new PdfRectangle(textLayoutInfo.LastPageRectangle); borderPdfRectangle.LineStyle.LineWidth = 0.5f; page1.Layout(borderPdfRectangle); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; #endregion #region Layout a text with width and height limits PdfText titleTextWithWidthAndHeight = new PdfText(crtXPos, crtYPos, "The text below is limited by a given width and height and is trimmed:", pdfFontBoldEmbed); titleTextWithWidthAndHeight.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTextWithWidthAndHeight); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; PdfText textWithWidthAndHeightLimit = new PdfText(crtXPos + 50, crtYPos, 300, 50, dummyText, pdfFont); textWithWidthAndHeightLimit.BackColor = System.Drawing.Color.WhiteSmoke; textLayoutInfo = page1.Layout(textWithWidthAndHeightLimit); // draw a rectangle around the text borderPdfRectangle = new PdfRectangle(textLayoutInfo.LastPageRectangle); borderPdfRectangle.LineStyle.LineWidth = 0.5f; page1.Layout(borderPdfRectangle); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; #endregion #region Layout a text with standard font PdfText textWithStandardFont = new PdfText(crtXPos, crtYPos, "This green text is written with a Helvetica Standard Type 1 font", helveticaStdFont); textWithStandardFont.BackColor = System.Drawing.Color.WhiteSmoke; textWithStandardFont.ForeColor = System.Drawing.Color.Green; textLayoutInfo = page1.Layout(textWithStandardFont); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; #endregion #region Layout a rotated text PdfText titleRotatedText = new PdfText(crtXPos, crtYPos, "The text below is rotated:", pdfFontBoldEmbed); titleRotatedText.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleRotatedText); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; // 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; string counterRotatedText = "This text is rotated 45 degrees counter clockwise"; // measure the rotated text size System.Drawing.SizeF counterRotatedTextSize = refGraphics.MeasureString(counterRotatedText, sysFont); // advance the Y position in the PDF page crtYPos += counterRotatedTextSize.Width / (float)Math.Sqrt(2) + 10; string clockwiseRotatedText = "This text is rotated 45 degrees clockwise"; PdfText rotatedCounterClockwiseText = new PdfText(crtXPos + 100, crtYPos, counterRotatedText, pdfFontEmbed); rotatedCounterClockwiseText.RotationAngle = 45; textLayoutInfo = page1.Layout(rotatedCounterClockwiseText); PdfText rotatedClockwiseText = new PdfText(crtXPos + 100, crtYPos, clockwiseRotatedText, pdfFontEmbed); rotatedClockwiseText.RotationAngle = -45; textLayoutInfo = page1.Layout(rotatedClockwiseText); // measure the rotated text size System.Drawing.SizeF clockwiseRotatedTextSize = refGraphics.MeasureString(clockwiseRotatedText, sysFont); // advance the Y position in the PDF page crtYPos += clockwiseRotatedTextSize.Width / (float)Math.Sqrt(2) + 10; // dispose the graphics used for measuring refGraphics.Dispose(); refBmp.Dispose(); #endregion #region Layout an automatically paginated text string dummyBigText = System.IO.File.ReadAllText(m_hostingEnvironment.ContentRootPath + @"\wwwroot" + @"\DemoFiles\Text\DummyBigText.txt"); PdfText titleTextPaginated = new PdfText(crtXPos, crtYPos, "The text below is automatically paginated when it gets to the bottom of this page:", pdfFontBoldEmbed); titleTextPaginated.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTextPaginated); // advance the Y position in the PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; PdfText paginatedText = new PdfText(crtXPos + 50, crtYPos, 300, dummyBigText, pdfFont); paginatedText.BackColor = System.Drawing.Color.WhiteSmoke; paginatedText.Cropping = false; textLayoutInfo = page1.Layout(paginatedText); // get the last page where the text was rendered PdfPage crtPage = document.Pages[textLayoutInfo.LastPageIndex]; // draw a line at the bottom of the text on the second page System.Drawing.PointF leftPoint = new System.Drawing.PointF(textLayoutInfo.LastPageRectangle.Left, textLayoutInfo.LastPageRectangle.Bottom); System.Drawing.PointF rightPoint = new System.Drawing.PointF(textLayoutInfo.LastPageRectangle.Right, textLayoutInfo.LastPageRectangle.Bottom); PdfLine borderLine = new PdfLine(leftPoint, rightPoint); borderLine.LineStyle.LineWidth = 0.5f; crtPage.Layout(borderLine); // advance the Y position in the second PDF page crtYPos += textLayoutInfo.LastPageRectangle.Height + 10; #endregion try { // write the PDF document to a memory buffer byte[] pdfBuffer = document.WriteToMemory(); FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf"); fileResult.FileDownloadName = "PdfText.pdf"; return(fileResult); } finally { document.Close(); } }
private void AddSignatureFooter(PdfPage pdfPage) { pdfPage.CreateFooterCanvas(300); pdfPage.Footer.Layout(new PdfHtml(20, 10, "<span style=\"font-family:Verdana; font-size:14px; color:black; text-decoration:none\">This is to certify that the data contained within this report was conducted as described above.</span>", null)); string signImageFile = HttpContext.Current.Server.MapPath(Utility.GetAPPSettingKey("ImageFolder") + "PHStudyReport/signiture.png"); PdfImage signImage = new PdfImage(20, 50, 218, Image.FromFile(signImageFile)); pdfPage.Footer.Layout(signImage); pdfPage.Footer.Layout(new PdfHtml(20, 260, "<p style=\"font-family:Verdana; font-size:14px; color:black; text-decoration:none\">Dr. N. W. Charter<br><br>Director, Profiling Services</p>", null)); Font pageFooterFont = new Font(new System.Drawing.FontFamily("Verdana"), 5, System.Drawing.GraphicsUnit.Point); pdfPage.Footer.Layout(new PdfHtml(0, 300, "<a href=\"http://www.discoverx.com\" style=\"font-family:Verdana; font-size:9px; color:black; text-decoration:none\">http://www.discoverx.com</a>", null)); string footerStr = string.Empty; // layout HTML in footer //footerHtml.FitDestHeight = true; PdfText centerText = new PdfText(10, 10, footerStr, pageFooterFont); centerText.HorizontalAlign = PdfTextHAlign.Center; centerText.EmbedSystemFont = true; centerText.ForeColor = System.Drawing.Color.Black; pdfPage.Footer.Layout(centerText); //htmlToPdfDocument.Footer.Layout(new PdfHtml(200, 5, footerStr, null)); PdfText rightText = new PdfText(10, 15, string.Format("Q{0} - {1}", DateTime.Now.GetQuarter(), DateTime.Now.Year), pageFooterFont); rightText.HorizontalAlign = PdfTextHAlign.Right; rightText.EmbedSystemFont = true; rightText.ForeColor = System.Drawing.Color.Black; pdfPage.Footer.Layout(rightText); // layout HTML in footer PdfHtml footerHtml = new PdfHtml(5, 5, footerStr, null); footerHtml.FitDestHeight = true; footerHtml.FontEmbedding = true; pdfPage.Footer.Layout(footerHtml); float footerHeight = pdfPage.Footer.Height; float footerWidth = pdfPage.Footer.Width; // add page numbering Font pageNumberFont = new Font(new FontFamily("Verdana"), 6, GraphicsUnit.Point); //pageNumberingFont.Mea PdfText pageNumberingText = new PdfText(5, footerHeight - 25, "{CrtPage}", pageNumberFont); pageNumberingText.HorizontalAlign = PdfTextHAlign.Center; pageNumberingText.EmbedSystemFont = true; pageNumberingText.ForeColor = Color.Black; pdfPage.Footer.Layout(pageNumberingText); }
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=="; // create the true type fonts that can be used in document System.Drawing.Font ttfFont = new System.Drawing.Font("Times New Roman", 10, System.Drawing.GraphicsUnit.Point); PdfFont newTimesFont = document.CreateFont(ttfFont); PdfFont newTimesFontEmbed = document.CreateFont(ttfFont, true); // create page 1 PdfPage page1 = document.AddPage(); // create a text object to be laid out on this page PdfText text1 = new PdfText(10, 10, "This is the Page 1 of the document with Open action", newTimesFontEmbed); // layout the text page1.Layout(text1); // create page 2 PdfPage page2 = document.AddPage(); // create a text object to be laid out on this page PdfText text2 = new PdfText(10, 10, "This is the Page 2 of the document with Open action", newTimesFontEmbed); // layout the text page2.Layout(text2); // create page 1 PdfPage page3 = document.AddPage(); // create a text object to be laid out on this page PdfText text3 = new PdfText(10, 10, "This is the Page 3 of the document with Open action", newTimesFontEmbed); // layout the text page3.Layout(text3); if (radioButtonJavaScript.Checked) { // display an alert message when the document is opened string alertMessage = textBoxAlertMessage.Text; string javaScriptCode = "app.alert({cMsg: \"" + alertMessage + "\", cTitle: \"Open Document JavaScript Action\"});"; // create the JavaScript action to display the alert PdfJavaScriptAction javaScriptAction = new PdfJavaScriptAction(javaScriptCode); // set the document JavaScript open action document.SetOpenAction(javaScriptAction); } else { // go to a given page in document and set the given zoom level when the document is opened int pageIndex = radioButtonPage1.Checked ? 0 : (radioButtonPage2.Checked ? 1 : 2); int zoomLevel = int.Parse(textBoxZoomLevel.Text); PdfDestination openDestination = new PdfDestination(document.Pages[pageIndex], new System.Drawing.PointF(10, 10)); openDestination.Zoom = zoomLevel; PdfGoToAction goToAction = new PdfGoToAction(openDestination); // set the document GoTo open action document.SetOpenAction(goToAction); } 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=OpenAction.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(); } }
private bool GetWord(PdfText text, int ci, out int si, out int ei) { si = ei = ci; if (text == null) return false; if (ci < 0) return false; for (int i = ci - 1; i >= 0; i--) { var c = text.GetCharacter(i); if ( char.IsSeparator(c) || char.IsPunctuation(c) || char.IsControl(c) || char.IsWhiteSpace(c) || c == '\r' || c == '\n' ) break; si = i; } int last = text.CountChars; for (int i = ci + 1; i < last; i++) { var c = text.GetCharacter(i); if ( char.IsSeparator(c) || char.IsPunctuation(c) || char.IsControl(c) || char.IsWhiteSpace(c) || c == '\r' || c == '\n' ) break; ei = i; } return true; }
public ActionResult CreatePdf(IFormCollection collection) { // 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(); FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf"); fileResult.FileDownloadName = "PdfOutlines.pdf"; return(fileResult); } finally { document.Close(); } }
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=="; // create a page in document PdfPage page1 = document.AddPage(); // create the true type fonts that can be used in document text 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); float crtYPos = 20; float crtXPos = 5; PdfLayoutInfo textLayoutInfo = null; PdfLayoutInfo graphicsLayoutInfo = null; #region Layout lines PdfText titleTextLines = new PdfText(crtXPos, crtYPos, "Lines:", pdfFontEmbed); titleTextLines.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTextLines); // advance the Y position in the PDF page crtYPos = textLayoutInfo.LastPageRectangle.Bottom + 10; // layout a simple line PdfLine pdfLine = new PdfLine(new System.Drawing.PointF(crtXPos, crtYPos), new System.Drawing.PointF(crtXPos + 60, crtYPos)); graphicsLayoutInfo = page1.Layout(pdfLine); // layout a thick line PdfLine pdfThickLine = new PdfLine(new System.Drawing.PointF(crtXPos + 70, crtYPos), new System.Drawing.PointF(crtXPos + 130, crtYPos)); pdfThickLine.LineStyle.LineWidth = 3; graphicsLayoutInfo = page1.Layout(pdfThickLine); // layout a dotted colored line PdfLine pdfDottedLine = new PdfLine(new System.Drawing.PointF(crtXPos + 140, crtYPos), new System.Drawing.PointF(crtXPos + 200, crtYPos)); pdfDottedLine.LineStyle.LineDashPattern = PdfLineDashPattern.Dot; pdfDottedLine.ForeColor = System.Drawing.Color.Green; graphicsLayoutInfo = page1.Layout(pdfDottedLine); // layout a dashed colored line PdfLine pdfDashedLine = new PdfLine(new System.Drawing.PointF(crtXPos + 210, crtYPos), new System.Drawing.PointF(crtXPos + 270, crtYPos)); pdfDashedLine.LineStyle.LineDashPattern = PdfLineDashPattern.Dash; pdfDashedLine.ForeColor = System.Drawing.Color.Green; graphicsLayoutInfo = page1.Layout(pdfDashedLine); // layout a dash-dot-dot colored line PdfLine pdfDashDotDotLine = new PdfLine(new System.Drawing.PointF(crtXPos + 280, crtYPos), new System.Drawing.PointF(crtXPos + 340, crtYPos)); pdfDashDotDotLine.LineStyle.LineDashPattern = PdfLineDashPattern.DashDotDot; pdfDashDotDotLine.ForeColor = System.Drawing.Color.Green; graphicsLayoutInfo = page1.Layout(pdfDashDotDotLine); // layout a thick line with rounded cap style PdfLine pdfRoundedLine = new PdfLine(new System.Drawing.PointF(crtXPos + 350, crtYPos), new System.Drawing.PointF(crtXPos + 410, crtYPos)); pdfRoundedLine.LineStyle.LineWidth = 5; pdfRoundedLine.LineStyle.LineCapStyle = PdfLineCapStyle.RoundCap; pdfRoundedLine.ForeColor = System.Drawing.Color.Blue; graphicsLayoutInfo = page1.Layout(pdfRoundedLine); // advance the Y position in the PDF page crtYPos += 10; #endregion #region Layout circles PdfText titleTextCircles = new PdfText(crtXPos, crtYPos, "Circles:", pdfFontEmbed); titleTextCircles.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTextCircles); // advance the Y position in the PDF page crtYPos = textLayoutInfo.LastPageRectangle.Bottom + 10; // draw a simple circle with solid line PdfCircle pdfCircle = new PdfCircle(new System.Drawing.PointF(crtXPos + 30, crtYPos + 30), 30); page1.Layout(pdfCircle); // draw a simple circle with dotted border line PdfCircle pdfDottedCircle = new PdfCircle(new System.Drawing.PointF(crtXPos + 100, crtYPos + 30), 30); pdfDottedCircle.ForeColor = System.Drawing.Color.Green; pdfDottedCircle.LineStyle.LineDashPattern = PdfLineDashPattern.Dot; graphicsLayoutInfo = page1.Layout(pdfDottedCircle); // draw a circle with colored border line and fill color PdfCircle pdfDisc = new PdfCircle(new System.Drawing.PointF(crtXPos + 170, crtYPos + 30), 30); pdfDisc.ForeColor = System.Drawing.Color.Navy; pdfDisc.BackColor = System.Drawing.Color.WhiteSmoke; graphicsLayoutInfo = page1.Layout(pdfDisc); // draw a circle with thick border line PdfCircle pdfThickBorderDisc = new PdfCircle(new System.Drawing.PointF(crtXPos + 240, crtYPos + 30), 30); pdfThickBorderDisc.LineStyle.LineWidth = 5; pdfThickBorderDisc.BackColor = System.Drawing.Color.LightSalmon; pdfThickBorderDisc.ForeColor = System.Drawing.Color.LightBlue; graphicsLayoutInfo = page1.Layout(pdfThickBorderDisc); crtYPos = graphicsLayoutInfo.LastPageRectangle.Bottom + 10; #endregion #region Layout ellipses and arcs PdfText titleTextEllipses = new PdfText(crtXPos, crtYPos, "Ellipses, arcs and slices:", pdfFontEmbed); titleTextEllipses.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTextEllipses); // advance the Y position in the PDF page crtYPos = textLayoutInfo.LastPageRectangle.Bottom + 10; // draw a simple ellipse with solid line PdfEllipse pdfEllipse = new PdfEllipse(new System.Drawing.PointF(crtXPos + 50, crtYPos + 30), 50, 30); graphicsLayoutInfo = page1.Layout(pdfEllipse); // draw an ellipse with fill color and colored border line PdfEllipse pdfFilledEllipse = new PdfEllipse(new System.Drawing.PointF(crtXPos + 160, crtYPos + 30), 50, 30); pdfFilledEllipse.BackColor = System.Drawing.Color.WhiteSmoke; pdfFilledEllipse.ForeColor = System.Drawing.Color.Green; graphicsLayoutInfo = page1.Layout(pdfFilledEllipse); // draw an ellipse arc with colored border line PdfEllipseArc pdfEllipseArc1 = new PdfEllipseArc(new System.Drawing.RectangleF(crtXPos + 220, crtYPos, 100, 60), 0, 90); pdfEllipseArc1.ForeColor = System.Drawing.Color.OrangeRed; pdfEllipseArc1.LineStyle.LineWidth = 3; graphicsLayoutInfo = page1.Layout(pdfEllipseArc1); // draw an ellipse arc with fill color and colored border line PdfEllipseArc pdfEllipseArc2 = new PdfEllipseArc(new System.Drawing.RectangleF(crtXPos + 220, crtYPos, 100, 60), 90, 90); pdfEllipseArc2.ForeColor = System.Drawing.Color.Navy; graphicsLayoutInfo = page1.Layout(pdfEllipseArc2); // draw an ellipse arc with fill color and colored border line PdfEllipseArc pdfEllipseArc3 = new PdfEllipseArc(new System.Drawing.RectangleF(crtXPos + 220, crtYPos, 100, 60), 180, 90); pdfEllipseArc3.ForeColor = System.Drawing.Color.Green; pdfEllipseArc3.LineStyle.LineWidth = 3; graphicsLayoutInfo = page1.Layout(pdfEllipseArc3); // draw an ellipse arc with fill color and colored border line PdfEllipseArc pdfEllipseArc4 = new PdfEllipseArc(new System.Drawing.RectangleF(crtXPos + 220, crtYPos, 100, 60), 270, 90); pdfEllipseArc4.ForeColor = System.Drawing.Color.Yellow; graphicsLayoutInfo = page1.Layout(pdfEllipseArc4); // draw an ellipse slice PdfEllipseSlice pdfEllipseSlice1 = new PdfEllipseSlice(new System.Drawing.RectangleF(crtXPos + 330, crtYPos, 100, 60), 0, 90); pdfEllipseSlice1.BackColor = System.Drawing.Color.Coral; graphicsLayoutInfo = page1.Layout(pdfEllipseSlice1); // draw an ellipse slice PdfEllipseSlice pdfEllipseSlice2 = new PdfEllipseSlice(new System.Drawing.RectangleF(crtXPos + 330, crtYPos, 100, 60), 90, 90); pdfEllipseSlice2.BackColor = System.Drawing.Color.LightBlue; graphicsLayoutInfo = page1.Layout(pdfEllipseSlice2); // draw an ellipse slice PdfEllipseSlice pdfEllipseSlice3 = new PdfEllipseSlice(new System.Drawing.RectangleF(crtXPos + 330, crtYPos, 100, 60), 180, 90); pdfEllipseSlice3.BackColor = System.Drawing.Color.LightGreen; graphicsLayoutInfo = page1.Layout(pdfEllipseSlice3); // draw an ellipse slice PdfEllipseSlice pdfEllipseSlice4 = new PdfEllipseSlice(new System.Drawing.RectangleF(crtXPos + 330, crtYPos, 100, 60), 270, 90); pdfEllipseSlice4.BackColor = System.Drawing.Color.Yellow; graphicsLayoutInfo = page1.Layout(pdfEllipseSlice4); crtYPos = graphicsLayoutInfo.LastPageRectangle.Bottom + 10; #endregion #region Layout rectangles PdfText titleTextRectangles = new PdfText(crtXPos, crtYPos, "Rectangles:", pdfFontEmbed); titleTextRectangles.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTextRectangles); // advance the Y position in the PDF page crtYPos = textLayoutInfo.LastPageRectangle.Bottom + 10; // draw a simple rectangle with solid line PdfRectangle pdfRectangle = new PdfRectangle(crtXPos, crtYPos, 100, 60); graphicsLayoutInfo = page1.Layout(pdfRectangle); // draw a rectangle with fill color and colored dotted border line PdfRectangle pdfFilledRectangle = new PdfRectangle(crtXPos + 110, crtYPos, 100, 60); pdfFilledRectangle.BackColor = System.Drawing.Color.WhiteSmoke; pdfFilledRectangle.ForeColor = System.Drawing.Color.Green; pdfFilledRectangle.LineStyle.LineDashPattern = PdfLineDashPattern.Dot; graphicsLayoutInfo = page1.Layout(pdfFilledRectangle); // draw a rectangle with fill color and without border line PdfRectangle pdfFilledNoBorderRectangle = new PdfRectangle(crtXPos + 220, crtYPos, 100, 60); pdfFilledNoBorderRectangle.BackColor = System.Drawing.Color.LightGreen; graphicsLayoutInfo = page1.Layout(pdfFilledNoBorderRectangle); // draw a rectangle filled with a thick border line and reounded corners PdfRectangle pdfThickBorderRectangle = new PdfRectangle(crtXPos + 330, crtYPos, 100, 60); pdfThickBorderRectangle.BackColor = System.Drawing.Color.LightSalmon; pdfThickBorderRectangle.ForeColor = System.Drawing.Color.LightBlue; pdfThickBorderRectangle.LineStyle.LineWidth = 5; pdfThickBorderRectangle.LineStyle.LineJoinStyle = PdfLineJoinStyle.RoundJoin; graphicsLayoutInfo = page1.Layout(pdfThickBorderRectangle); crtYPos = graphicsLayoutInfo.LastPageRectangle.Bottom + 10; #endregion #region Layout Bezier curves PdfText titleTextBezier = new PdfText(crtXPos, crtYPos, "Bezier curves and polygons:", pdfFontEmbed); titleTextBezier.ForeColor = System.Drawing.Color.Navy; textLayoutInfo = page1.Layout(titleTextBezier); // advance the Y position in the PDF page crtYPos = textLayoutInfo.LastPageRectangle.Bottom + 10; // the points controlling the Bezier curve System.Drawing.PointF pt1 = new System.Drawing.PointF(crtXPos, crtYPos + 50); System.Drawing.PointF pt2 = new System.Drawing.PointF(crtXPos + 50, crtYPos); System.Drawing.PointF pt3 = new System.Drawing.PointF(crtXPos + 100, crtYPos + 100); System.Drawing.PointF pt4 = new System.Drawing.PointF(crtXPos + 150, crtYPos + 50); // draw controlling points PdfCircle pt1Circle = new PdfCircle(pt1, 2); pt1Circle.BackColor = System.Drawing.Color.LightSalmon; page1.Layout(pt1Circle); PdfCircle pt2Circle = new PdfCircle(pt2, 2); pt2Circle.BackColor = System.Drawing.Color.LightSalmon; page1.Layout(pt2Circle); PdfCircle pt3Circle = new PdfCircle(pt3, 2); pt3Circle.BackColor = System.Drawing.Color.LightSalmon; page1.Layout(pt3Circle); PdfCircle pt4Circle = new PdfCircle(pt4, 2); pt4Circle.BackColor = System.Drawing.Color.LightSalmon; page1.Layout(pt4Circle); // draw the Bezier curve PdfBezierCurve bezierCurve = new PdfBezierCurve(pt1, pt2, pt3, pt4); bezierCurve.ForeColor = System.Drawing.Color.LightBlue; bezierCurve.LineStyle.LineWidth = 2; graphicsLayoutInfo = page1.Layout(bezierCurve); #endregion #region Layout a polygons // layout a polygon without fill color // the polygon points System.Drawing.PointF[] polyPoints = new System.Drawing.PointF[] { new System.Drawing.PointF(crtXPos + 200, crtYPos + 50), new System.Drawing.PointF(crtXPos + 250, crtYPos), new System.Drawing.PointF(crtXPos + 300, crtYPos + 50), new System.Drawing.PointF(crtXPos + 250, crtYPos + 100) }; // draw polygon points foreach (System.Drawing.PointF polyPoint in polyPoints) { PdfCircle pointCircle = new PdfCircle(polyPoint, 2); pointCircle.BackColor = System.Drawing.Color.LightSalmon; page1.Layout(pointCircle); } // draw the polygon line PdfPolygon pdfPolygon = new PdfPolygon(polyPoints); pdfPolygon.ForeColor = System.Drawing.Color.LightBlue; pdfPolygon.LineStyle.LineWidth = 2; pdfPolygon.LineStyle.LineCapStyle = PdfLineCapStyle.ProjectingSquareCap; graphicsLayoutInfo = page1.Layout(pdfPolygon); // layout a polygon with fill color // the polygon points System.Drawing.PointF[] polyFillPoints = new System.Drawing.PointF[] { new System.Drawing.PointF(crtXPos + 330, crtYPos + 50), new System.Drawing.PointF(crtXPos + 380, crtYPos), new System.Drawing.PointF(crtXPos + 430, crtYPos + 50), new System.Drawing.PointF(crtXPos + 380, crtYPos + 100) }; // draw a polygon with fill color and thick rounded border PdfPolygon pdfFillPolygon = new PdfPolygon(polyFillPoints); pdfFillPolygon.ForeColor = System.Drawing.Color.LightBlue; pdfFillPolygon.BackColor = System.Drawing.Color.LightSalmon; pdfFillPolygon.LineStyle.LineWidth = 5; pdfFillPolygon.LineStyle.LineCapStyle = PdfLineCapStyle.RoundCap; pdfFillPolygon.LineStyle.LineJoinStyle = PdfLineJoinStyle.RoundJoin; graphicsLayoutInfo = page1.Layout(pdfFillPolygon); #endregion 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=PdfGraphics.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(); } }
private void Append(int pageIdx, Span span, StringBuilder str) { PdfPage page = Document.Pages[pageIdx]; PdfText pdfText = page.Text; // Get all text objects TextObject GetTextObject(PdfTextObject textObj) { var bbox = textObj.GetCharRect(0); var absIdx = pdfText.GetCharIndexAtPos(bbox.left, bbox.top, 1, 1); return(new TextObject(textObj, absIdx)); } var textObjects = page.PageObjects .Where(o => o.ObjectType == PageObjectTypes.PDFPAGE_TEXT) .Select(o => GetTextObject((PdfTextObject)o)) .OrderBy(t => t.StartIndex) .ToList(); // Some PDF documents are improperly formatted and miss PdfTextObjects -- Fill the gaps int lastEndIdx = textObjects.FirstOrDefault()?.EndIndex ?? 0; for (int i = 1; i < textObjects.Count; i++) { var textObj = textObjects[i]; if (textObj.StartIndex <= lastEndIdx + 1) // This shouldn't be < -- But allow it nevertheless { lastEndIdx = textObj.EndIndex; continue; } var gapTextObj = new TextObject(textObjects[i - 1], lastEndIdx + 1, textObj.StartIndex - lastEndIdx - 1); textObjects.Insert(i++, gapTextObj); lastEndIdx = textObj.EndIndex; } // Build the HTML tags int shift = str.Length; foreach (var textObj in textObjects) { // Check overlap var objSpan = new Span(textObj.StartIndex, textObj.StartIndex + textObj.Length - 1); if (objSpan.Overlaps(span, out var overlap) == false) { continue; } // Look behind for line return, and extend span for inclusion -- Unlike PdfTextObjects, GetText includes \r\n int lookbackIdx = textObj.StartIndex - 2; int tagStartIdxExtendBehind = 0; if (lookbackIdx >= span.StartIdx && pdfText.GetText(lookbackIdx, 2) is "\r\n") { tagStartIdxExtendBehind = -2; } // Generate text object tag var relStartIdx = shift + overlap.StartIdx - span.StartIdx; var tag = new HtmlTagSpan(new Span(relStartIdx + tagStartIdxExtendBehind, relStartIdx + overlap.Length - 1)) .WithStyle(s => SetTextStyle(s, textObj)); HtmlTags.Add(tag); // Generate extract tag if (OverlapsWithExtract(pageIdx, overlap, out var extractOverlaps)) { foreach (var extractOverlap in extractOverlaps) { int extractStartIdx = shift + extractOverlap.StartIdx - span.StartIdx; var extractSpan = new Span(extractStartIdx, extractStartIdx + extractOverlap.Length - 1); var extractTag = new HtmlTagSpan(extractSpan, 100); extractTag.WithStyle(s => s.WithBackgroundColorColor(extractOverlap.Object)); HtmlTags.Add(extractTag); } } } str.Append(pdfText.GetText(span.StartIdx, span.Length)); }
private void SetFooter(PdfDocument document, string fileName = "") { //create the document footer document.CreateFooterCanvas(45); string logoImageFile = HttpContext.Current.Server.MapPath(Utility.GetAPPSettingKey("ImageFolder") + "PDFCover/DRx_logo_2013.png"); PdfImage logoImage = new PdfImage(5, 5, 40, Image.FromFile(logoImageFile)); document.Footer.Layout(logoImage); Font pageFooterFont = new Font(new System.Drawing.FontFamily("Verdana"), 5, System.Drawing.GraphicsUnit.Point); document.Footer.Layout(new PdfHtml(0, 10, "<a href=\"http://www.discoverx.com\" style=\"font-family:Verdana; font-size:9px; color:black; text-decoration:none\">http://www.discoverx.com</a>", null)); string footerStr = string.Empty; if (fileName == "DRx_Price_List_") { footerStr = PRICE_LIST_FOOTER; } else if (fileName == "DRx_Target_List_") { footerStr = TARGET_LIST_FOOTER; } // layout HTML in footer //footerHtml.FitDestHeight = true; PdfText centerText = new PdfText(10, 10, footerStr, pageFooterFont); centerText.HorizontalAlign = PdfTextHAlign.Center; centerText.EmbedSystemFont = true; centerText.ForeColor = System.Drawing.Color.Black; document.Footer.Layout(centerText); //htmlToPdfDocument.Footer.Layout(new PdfHtml(200, 5, footerStr, null)); PdfText rightText = new PdfText(10, 15, string.Format("Q{0} - {1}", DateTime.Now.GetQuarter(), DateTime.Now.Year), pageFooterFont); rightText.HorizontalAlign = PdfTextHAlign.Right; rightText.EmbedSystemFont = true; rightText.ForeColor = System.Drawing.Color.Black; document.Footer.Layout(rightText); // layout HTML in footer PdfHtml footerHtml = new PdfHtml(5, 5, footerStr, null); footerHtml.FitDestHeight = true; footerHtml.FontEmbedding = true; document.Footer.Layout(footerHtml); float footerHeight = document.Footer.Height; float footerWidth = document.Footer.Width; // add page numbering Font pageNumberFont = new Font(new FontFamily("Verdana"), 6, GraphicsUnit.Point); //pageNumberingFont.Mea PdfText pageNumberingText = new PdfText(5, footerHeight - 25, "Page {CrtPage}", pageNumberFont); pageNumberingText.HorizontalAlign = PdfTextHAlign.Center; pageNumberingText.EmbedSystemFont = true; pageNumberingText.ForeColor = Color.Black; document.Footer.Layout(pageNumberingText); //string footerImageFile = Application.StartupPath + @"\DemoFiles\Images\HiQPdfLogo.png"; //PdfImage logoFooterImage = new PdfImage(footerWidth - 40 - 5, 5, 40, Image.FromFile(footerImageFile)); //document.Footer.Layout(logoFooterImage); //// create a border for footer //PdfRectangle borderRectangle = new PdfRectangle(1, 1, footerWidth - 2, footerHeight - 2); //borderRectangle.LineStyle.LineWidth = 0.5f; //borderRectangle.ForeColor = Color.DarkGreen; //document.Footer.Layout(borderRectangle); }
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 attachments when the document is opened document.Viewer.PageMode = PdfPageMode.Attachments; // create a page in document PdfPage page1 = document.AddPage(); // 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); // 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 an attachment with icon from file string filePath1 = Server.MapPath("~") + @"\DemoFiles\Attach\TextAttach1.txt"; PdfAttachment pdfAttachment1 = document.CreateAttachmentFromFile(page1, new System.Drawing.RectangleF(10, 30, 10, 20), PdfAttachIconType.PushPin, filePath1); pdfAttachment1.Description = "Attachment with icon from a file"; // write a description at the right of the icon PdfText pdfAttachment1Descr = new PdfText(40, 35, pdfAttachment1.Description, pdfFontEmbed); page1.Layout(pdfAttachment1Descr); // create an attachment with icon from a stream // The stream must remain opened until the document is saved System.IO.FileStream fileStream2 = new System.IO.FileStream(filePath1, System.IO.FileMode.Open, System.IO.FileAccess.Read); PdfAttachment pdfAttachment2 = document.CreateAttachmentFromStream(page1, new System.Drawing.RectangleF(10, 60, 10, 20), PdfAttachIconType.Paperclip, fileStream2, "AttachFromStream_WithIcon.txt"); pdfAttachment2.Description = "Attachment with icon from a stream"; // write a description at the right of the icon PdfText pdfAttachment2Descr = new PdfText(40, 65, pdfAttachment2.Description, pdfFontEmbed); page1.Layout(pdfAttachment2Descr); // create an attachment without icon in PDF from a file string filePath2 = Server.MapPath("~") + @"\DemoFiles\Attach\TextAttach2.txt"; document.CreateAttachmentFromFile(filePath2); // create an attachment without icon in PDF from a stream // The stream must remain opened until the document is saved System.IO.FileStream fileStream1 = new System.IO.FileStream(filePath2, System.IO.FileMode.Open, System.IO.FileAccess.Read); document.CreateAttachmentFromStream(fileStream1, "AttachFromStream_NoIcon.txt"); // 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(); fileStream1.Close(); } }
public FileResult DownloadPDF(int id) { using (var eRepository = new ECollateralRepository()) { var data = eRepository.GetItemInformation(id); /* * var pdfEXE = ConfigurationManager.AppSettings["ePubPDFTool"]; * var fileName = Path.Combine( ConfigurationManager.AppSettings["ePubPDFLocation"], Guid.NewGuid() + ".pdf" ); * var customUrl = MyPaoliURLLocal() + "/info/" + data.Settings.CustomURL; * * var process = System.Diagnostics.Process.Start( pdfEXE, string.Format( "\"{0}\" \"{1}\"", customUrl, fileName ) ); * * while( !process.HasExited ) * { * System.Threading.Thread.Sleep( 500 ); * } * * return File( fileName, "application/pdf", string.Format( data.Settings.CustomURL + ".pdf" ) );*/ // create the HTML to PDF converter HtmlToPdf htmlToPdfConverter = new HtmlToPdf(); htmlToPdfConverter.SerialNumber = "iMDh2djs-7sTh6vrp-+vGwprio-uai6qLC9-vai7uaa5-uqaxsbGx"; // set PDF page size and orientation htmlToPdfConverter.Document.PageSize = PdfPageSize.Letter; htmlToPdfConverter.Document.PageOrientation = PdfPageOrientation.Portrait; htmlToPdfConverter.BrowserWidth = 1000; // set PDF page margins htmlToPdfConverter.Document.Margins = new PdfMargins(10); // enable header htmlToPdfConverter.Document.Header.Enabled = true; htmlToPdfConverter.Document.Header.Height = 25; // enable footer htmlToPdfConverter.Document.Footer.Enabled = true; // set footer height htmlToPdfConverter.Document.Footer.Height = 30; // set footer background color htmlToPdfConverter.Document.Footer.BackgroundColor = System.Drawing.Color.White; float pdfPageWidth = htmlToPdfConverter.Document.PageOrientation == PdfPageOrientation.Portrait ? htmlToPdfConverter.Document.PageSize.Width : htmlToPdfConverter.Document.PageSize.Height; float footerWidth = pdfPageWidth - htmlToPdfConverter.Document.Margins.Left - htmlToPdfConverter.Document.Margins.Right; float footerHeight = htmlToPdfConverter.Document.Footer.Height; // layout HTML in footer /* PdfHtml footerHtml = new PdfHtml( 5, 5, @"View this version online at [URL]", null ); * footerHtml.FitDestHeight = true; * htmlToPdfConverter.Document.Footer.Layout( footerHtml ); */ // add page numbering System.Drawing.Font pageNumberingFont = new System.Drawing.Font(new System.Drawing.FontFamily("Helvetica"), 8, System.Drawing.GraphicsUnit.Pixel); PdfLine footerLine = new PdfLine(new System.Drawing.PointF(0, 0), new System.Drawing.PointF(footerWidth - 1, 0)); footerLine.ForeColor = new PdfColor(0xAF, 0xAF, 0xAF); footerLine.LineStyle.LineWidth = 1.0f; htmlToPdfConverter.Document.Footer.Layout(footerLine); var customUrl = MyPaoliURL() + "/info/" + data.Settings.CustomURL; PdfText urlFooterText = new PdfText(25, footerHeight - 25, "View online at " + customUrl, pageNumberingFont); urlFooterText.HorizontalAlign = PdfTextHAlign.Left; urlFooterText.EmbedSystemFont = true; urlFooterText.ForeColor = new PdfColor(102, 102, 102); htmlToPdfConverter.Document.Footer.Layout(urlFooterText); PdfText pageNumberingText = new PdfText(5, footerHeight - 25, "Page {CrtPage} of {PageCount}" + new string( ' ', 15 ), pageNumberingFont); pageNumberingText.HorizontalAlign = PdfTextHAlign.Right; pageNumberingText.EmbedSystemFont = true; pageNumberingText.ForeColor = new PdfColor(102, 102, 102); htmlToPdfConverter.Document.Footer.Layout(pageNumberingText); htmlToPdfConverter.PageCreatingEvent += new PdfPageCreatingDelegate(htmlToPdfConverter_PageCreatingEvent); // convert HTML to PDF byte[] pdfBuffer = null; // convert URL to a PDF memory buffer string url = MyPaoliURLLocal() + "/ePublisher/GeneratePDF/" + data.Settings.CustomURL; pdfBuffer = htmlToPdfConverter.ConvertUrlToMemory(url); return(File(pdfBuffer, "application/pdf", data.Settings.CustomURL + ".pdf")); } }