public static void Html2Pdf(string htmlText, string tempPdfPath, string paperName, string direction) { if (string.IsNullOrEmpty(htmlText)) { throw new Exception("传入的html无内容:" + htmlText); } MemoryStream outputStream = new MemoryStream(); //实例化MemoryStream,用于存PDF byte[] data = Encoding.UTF8.GetBytes(htmlText); //字串转成byte[] MemoryStream msInput = new MemoryStream(data); paperName = paperName ?? "A4"; int width = 0, height = 0; PrintUtils.getPaperSize(paperName, ref width, ref height); Rectangle pageSize = new Rectangle(width, height); //设置pdf模板大小 if (direction == "2") //2:横向打印 { pageSize = new Rectangle(height, width); } Document doc = new Document(pageSize); //要写PDF的文件 document = new Document(PageSize.A4, 25, 25, 30, 30); PdfWriter writer = PdfWriter.GetInstance(doc, outputStream); //指定文件预设开档时的缩放为100% PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f); //开启Document文件 doc.Open(); //使用XMLWorkerHelper把Html parse到PDF档里 XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory()); //XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8); //将pdfDest设定的资料写到PDF档 PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer); writer.SetOpenAction(action); doc.Close(); msInput.Close(); outputStream.Close(); //回传PDF档案 var bytes = outputStream.ToArray(); var ret = Convert.ToBase64String(bytes); try { string strbase64 = ret; strbase64 = strbase64.Replace(' ', '+'); System.IO.MemoryStream stream = new System.IO.MemoryStream(Convert.FromBase64String(strbase64)); System.IO.FileStream fs = new System.IO.FileStream(tempPdfPath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); byte[] b = stream.ToArray(); //byte[] b = stream.GetBuffer(); fs.Write(b, 0, b.Length); fs.Close(); } catch (Exception ex) { } }
/// <summary> /// 将html文本输出到pdf文档中 /// </summary> /// <param name="fileName">pdf文档完整路径</param> /// <param name="htmlText">html文档</param> /// <returns></returns> private static Result convertHtmlTextToPDF(string fileName, string htmlText) { Result model = new Result(); try { MemoryStream outputStream = new MemoryStream(); byte[] data = Encoding.UTF8.GetBytes(htmlText); MemoryStream msInput = new MemoryStream(data); Document doc = new Document(); PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(fileName, FileMode.Create)); PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f); doc.Open(); XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new PDFChineseFontFactory()); PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer); writer.SetOpenAction(action); doc.Close(); msInput.Close(); outputStream.Close(); model.Flag = true; model.Message = fileName; } catch (Exception ex) { model.Flag = false; model.Message = ex.Message; } return(model); }
public void Complete() { int viewerPreferences = 0; // Open bookmark panel when displaying if (displayPdf.PageModeUseOutlines) { viewerPreferences |= PdfWriter.PageModeUseOutlines; } // Set page layout switch (displayPdf.PageLayout) { case PageLayout.SinglePage: viewerPreferences |= PdfWriter.PageLayoutSinglePage; break; case PageLayout.OneColumn: viewerPreferences |= PdfWriter.PageLayoutOneColumn; break; } copy.ViewerPreferences = viewerPreferences; // Fit to page height when displayed var dest = new PdfDestination(PdfDestination.FITV); var action = PdfAction.GotoLocalPage(1, dest, copy); copy.SetOpenAction(action); SetProperty(); ChangeBookmark(rootBookmarks); copy.Outlines = rootBookmarks; }
// --------------------------------------------------------------------------- /** * Manipulates a PDF file src with the file dest as result * @param src the original PDF */ public byte[] ManipulatePdf(byte[] src) { // Create the reader PdfReader reader = new PdfReader(src); int n = reader.NumberOfPages; using (MemoryStream ms = new MemoryStream()) { // Create the stamper using (PdfStamper stamper = new PdfStamper(reader, ms)) { // Make a list with all the possible actions actions = new List <PdfAction>(); PdfDestination d; for (int i = 0; i < n;) { d = new PdfDestination(PdfDestination.FIT); actions.Add(PdfAction.GotoLocalPage(++i, d, stamper.Writer)); } // Add a navigation table to every page PdfContentByte canvas; for (int i = 0; i < n;) { canvas = stamper.GetOverContent(++i); CreateNavigationTable(i, n).WriteSelectedRows(0, -1, 696, 36, canvas); } } return(ms.ToArray()); } }
public Chap1105() { Console.WriteLine("Chapter 11 example 5: Open action"); // step 1: creation of a document-object Document document = new Document(PageSize.A4, 50, 50, 50, 50); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("Chap1105.pdf", FileMode.Create)); // step 3: we open the document document.Open(); // step 4: we add content PdfAction action = PdfAction.GotoLocalPage(2, new PdfDestination(PdfDestination.XYZ, -1, 10000, 0), writer); writer.SetOpenAction(action); document.Add(new Paragraph("Page 1")); document.NewPage(); document.Add(new Paragraph("Page 2")); } catch (Exception de) { Console.Error.WriteLine(de.Message); Console.Error.WriteLine(de.StackTrace); } // step 5: we close the document document.Close(); }
public byte[] ConvertHtmlTextToPDF(string htmlText) { if (string.IsNullOrEmpty(htmlText)) { return(null); } //避免當htmlText無任何html tag標籤的純文字時,轉PDF時會掛掉,所以一律加上<p>標籤 htmlText = "<p>" + htmlText + "</p>"; //System.IO.MemoryStream MemoryStream outputStream = new MemoryStream(); //要把PDF寫到哪個串流 byte[] data = Encoding.UTF8.GetBytes(htmlText); //字串轉成byte[] MemoryStream msInput = new MemoryStream(data); Document doc = new Document(); //要寫PDF的文件,建構子沒填的話預設直式A4 PdfWriter writer = PdfWriter.GetInstance(doc, outputStream); //指定文件預設開檔時的縮放為100% PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f); //開啟Document文件 doc.Open(); //使用XMLWorkerHelper把Html parse到PDF檔裡 XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory()); //將pdfDest設定的資料寫到PDF檔 PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer); writer.SetOpenAction(action); doc.Close(); msInput.Close(); outputStream.Close(); //回傳PDF檔案 return(outputStream.ToArray()); }
public byte[] ConvertHtmlTextToPDF(string htmltext) { if (string.IsNullOrEmpty(htmltext)) { return(null); } //避免htmlText没有任何html tag标签的純文字时,转PDF时会挂掉,所以一律加上<p>标签 //htmlText = "<p>" + htmltext + "</p>"; MemoryStream stream = new MemoryStream(); byte[] data = Encoding.UTF8.GetBytes(htmltext); MemoryStream msInput = new MemoryStream(data); Document doc = new Document(); PdfWriter writer = PdfWriter.GetInstance(doc, stream); //指定文件默认缩放标准100% PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f); doc.Open(); //使用XMLWorkerHelper把Html parse到PDF XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory()); //將pdfDest 写入到PDF PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer); writer.SetOpenAction(action); doc.Close(); msInput.Close(); stream.Close(); //回传PDF return(stream.ToArray()); }
/// <summary> /// 注意事项 /// 1:html标签必须闭合,符合规范 /// 2:目前暂不支持link样式导入,只能写style /// 使用示例: /// WebClient wc = new WebClient(); /// 从网址下载Html字串 /// string htmlText = wc.DownloadString("http://localhost:6953/test.html"); /// byte[] pdfFile = PdfHelper.ConvertHtmlTextToPdf(htmlText); /// return File(pdfFile, "application/pdf", "测试.pdf"); /// </summary> /// <param name="htmlText">html格式的字符串</param> /// <returns></returns> public static byte[] ConvertHtmlTextToPdf(string htmlText) { if (string.IsNullOrEmpty(htmlText)) { return(null); } //避免当htmlText无任何html tag标签的纯文字时,转PDF时会挂掉,所以一律加上<p>标签 htmlText = "<p>" + htmlText + "</p>"; MemoryStream outputStream = new MemoryStream(); //要把PDF写到哪个串流 byte[] data = Encoding.UTF8.GetBytes(htmlText); //字串转成byte[] MemoryStream msInput = new MemoryStream(data); Document doc = new Document(); //要写PDF的文件,建构子没填的话预设直式A4 PdfWriter writer = PdfWriter.GetInstance(doc, outputStream); //指定文件预设开档时的缩放为100% PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f); //开启Document文件 doc.Open(); //使用XMLWorkerHelper把Html parse到PDF档里 XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory()); //将pdfDest设定的资料写到PDF档 PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer); writer.SetOpenAction(action); doc.Close(); msInput.Close(); outputStream.Close(); //回传PDF档案 return(outputStream.ToArray()); }
public static string Combine(string[] files, string pdfFileName) { if (!files.Any()) { return("empty"); } string outputPdfPath = Path.Combine(new DirectoryInfo(files[0]).Parent.Parent.FullName, pdfFileName + ".pdf"); try { using (FileStream stream = new FileStream(outputPdfPath, FileMode.Create)) using (Document doc = new Document()) using (PdfCopy pdf = new PdfCopy(doc, stream)) { doc.Open(); doc.AddTitle(pdfFileName); /* * doc.NewPage(); * doc.Add(new Paragraph(pdfFileName)); * doc.Add(new Paragraph("power by ")); * Anchor anchor = new Anchor("html2pdf"); * anchor.Reference = "https://github.com/xiangwan/html2pdf"; * doc.Add(anchor);*/ var rootOutline = pdf.RootOutline; PdfReader reader = null; PdfImportedPage page = null; PdfContentByte cb = pdf.DirectContent; PdfWriter wrt = cb.PdfWriter; var pageIndex = 1; files.ToList().ForEach(file => { reader = new PdfReader(file); var n = reader.NumberOfPages; for (int i = 0; i < n; i++) { page = pdf.GetImportedPage(reader, i + 1); pdf.AddPage(page); } var title = new FileInfo(file).Name.Replace(".pdf", ""); var oline = new PdfOutline(rootOutline, PdfAction.GotoLocalPage(pageIndex, new PdfDestination(pageIndex), wrt), title); rootOutline.AddKid(oline); pageIndex += n; pdf.FreeReader(reader); reader.Close(); }); } } catch (Exception ex) { logger.Error(ex); return("error." + ex.Message); } return("ok"); }
private void addBookmark(PdfReader reader) { var subject = getSubject(reader); var rootOutline = _writer.DirectContent.RootOutline; var name = Guid.NewGuid().ToString(); _document.Add(new Chunk(" ").SetLocalDestination(name)); new PdfOutline(rootOutline, PdfAction.GotoLocalPage(name, false), subject); _writer.ViewerPreferences = PdfWriter.PageModeUseOutlines; }
private int CreateTableOfContent(PdfTableOfContent toc, PdfWriter writer, Document doc, bool reorderPage) { var numberOfPageBeforeInsertTOC = writer.PageNumber; doc.SetPageSize(PageSize.A4); doc.SetMargins(36, 36, 36, 36); doc.NewPage(); Paragraph p; PdfAction action = new PdfAction(PdfAction.FIRSTPAGE); PdfAnnotation link; if (!String.IsNullOrEmpty(toc.TitreDocument)) { p = new Paragraph(toc.TitreDocument, fontTitrePrincipal); p.Alignment = Element.ALIGN_CENTER; doc.Add(p); // Un espace ? peut mieux faire peut etre... doc.Add(new Paragraph(" ")); } foreach (var content in toc.Contents) { // action = PdfAction.GotoLocalPage("p" + content.RealPage, new PdfDestination(PdfDestination.XYZ, 0f, PageSize.A4.Top, 0f), writer); action = PdfAction.GotoLocalPage("p" + content.RealPage, false); p = new Paragraph(content.Titre, fontText); p.Add(new Chunk(new DottedLineSeparator())); p.Add(new Chunk(content.PageNumber.ToString(), fontText)); float topY = writer.GetVerticalPosition(false); doc.Add(p); float bottomYY = writer.GetVerticalPosition(false); if (bottomYY > topY) // on a changé de page { topY = _docContent.Top; } link = new PdfAnnotation(writer, doc.Left, bottomYY, doc.Right, topY, action); writer.AddAnnotation(link); } var numberOfPage = writer.PageNumber; if (reorderPage) { doc.NewPage(); var reorderArray = Enumerable.Range(numberOfPageBeforeInsertTOC + 1, numberOfPage - numberOfPageBeforeInsertTOC) .Concat(Enumerable.Range(1, numberOfPageBeforeInsertTOC)).ToArray(); writer.ReorderPages(reorderArray); } return(numberOfPage); }
private void Visit(PdfOutline parentOutline, OutlineNode node) { if (node == null) { return; } var counterString = Path(node); var thisOutline = new PdfOutline(parentOutline, PdfAction.GotoLocalPage(counterString, false), node.Title.ToString()); Visit(thisOutline, node.FirstChild()); Visit(parentOutline, node.NextSibling()); }
private void setInitialDocumentZoomPercent() { if (PageSetup.ViewerPreferences == null) { return; } var zoom = PageSetup.ViewerPreferences.ZoomPercent.ApproxEquals(0) ? 1 : PageSetup.ViewerPreferences.ZoomPercent / 100; var pdfDest = new PdfDestination(PdfDestination.XYZ, 0, PdfDoc.PageSize.Height, zoom); var action = PdfAction.GotoLocalPage(1, pdfDest, PdfWriter); PdfWriter.SetOpenAction(action); }
/// <summary> /// <para>(ESP) Este metodo es recursivo, se encarga de asignar los bookmarks y asignarles su parent</para> /// <para>(ENG) this method is recursive, assign the parent for each file</para> /// </summary> /// <param name="doc"> /// <para>(ESP) Este es el documento actual</para> /// <para>(ENG) this is the current document</para> /// </param> /// <param name="pdfCopy"> /// <para>(ESP)es el documento que hará el smart copy</para> /// <para>(ENG) this is the pdfsmartcopy for the append another pdf</para> /// </param> /// <param name="marcadorNombreLibro"> /// <para>(ESP) este es el parent</para> /// <para>(ENG) this is the parent</para> /// </param> /// <param name="enlace"> /// <para>(ESP) Esta es la estructura del documento, donde contiene nombre y url del documento</para> /// <para>(ENG) This is the structure's document, this contains the name and url's file </para> /// </param> /// <param name="rutaPDFs"> /// <para>(ESP)Es donde se generan los documentos</para> /// <para>(ENG)Its the path for create the files</para> /// </param> public static void GenerarHijosEstructura(Document doc, PdfSmartCopy pdfCopy, PdfOutline marcadorNombreLibro, Modelo.POCOs.EstructuraPDF enlace, string rutaPDFs) { try { PdfContentByte pb = pdfCopy.DirectContent; //Crea el link para la sección Anchor section1 = new Anchor(enlace.Nombre) { Name = enlace.Nombre }; Paragraph psecton1 = new Paragraph(); psecton1.Add(section1); //mostrar la sección 1 en una ubicación específica del documento ColumnText.ShowTextAligned(pb, Element.ALIGN_LEFT, psecton1, 36, PageSize.A4.Height - 100, 0); //(ESP) Se crea el marcador para este documento, se hace referencia al documento padre (parent) //(ENG) create the bookmark for this document, and create the reference with the parent var mbot = new PdfOutline(marcadorNombreLibro, PdfAction.GotoLocalPage(enlace.Nombre, false), enlace.Nombre); //(ESP) Se lee el documento //(ENG) read the file PdfReader reader = new PdfReader(enlace.UrlDocumento); //(ESP) Se adjuntan las paginas al documento //(ENG) Copy each page in the current pdfcopy for (int I = 1; I <= reader.NumberOfPages; I++) { doc.SetPageSize(reader.GetPageSizeWithRotation(1)); PdfImportedPage page = pdfCopy.GetImportedPage(reader, I); pdfCopy.AddPage(page); } //Clean up pdfCopy.FreeReader(reader); reader.Close(); if (enlace.Hijos.Any()) { foreach (var cadaHijo in enlace.Hijos) { //(ESP) aquí está la clave, esto es recurisvo //(ENG) this is the magic, its recursive GenerarHijosEstructura(doc, pdfCopy, mbot, cadaHijo, rutaPDFs); } } } catch (Exception error) { } }
//public static string WebResult(string Server, int PurchaseRequestID) //{ // string _path = "/Purchase/PRForm?PurchaseRequestID=" + PurchaseRequestID; // WebClient _wc = new WebClient(); // _wc.Encoding=Encoding.UTF8; // string _content = _wc.DownloadString(_path); // return _content; //} private static byte[] Html2PDF(string Content, string BussinessType) { //return null; if (string.IsNullOrEmpty(Content)) { return(null); } MemoryStream oStream = new MemoryStream(); byte[] data = Encoding.UTF8.GetBytes(Content); MemoryStream iStream = new MemoryStream(data); Document doc = new Document(PageSize.A4, 25, 25, 100, 50); PdfWriter writer = PdfWriter.GetInstance(doc, oStream); PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f); doc.Open(); #region 页眉页脚 switch (BussinessType) { case "PO": writer.PageEvent = new HeaderAndFooterEvent(); HeaderAndFooterEvent.PAGE_NUMBER = true; HeaderAndFooterEvent.tpl = writer.DirectContent.CreateTemplate(0, 0); break; case "QR": break; } #endregion try { //doc.Add(_image); XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, iStream, null, Encoding.UTF8, new UnicodeFontFactory()); PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer); writer.SetOpenAction(action); doc.Close(); } catch (Exception ex) { throw ex; } finally { iStream.Close(); oStream.Close(); } return(oStream.ToArray()); }
public void AddBookContents(PdfWriter writer, PdfOutline outline, BookContentNode content) { foreach (BookContentNode contentnode in content.Children) { int page = contentnode.Bookcontent.Page; if (page > _book.PagesNum) { break; } page += _frontpagesinfo.DownloadedPages; PdfAction action = PdfAction.GotoLocalPage(page, new PdfDestination(PdfDestination.FITB), writer); AddBookContents(writer, new PdfOutline(outline, action, contentnode.Bookcontent.Title), contentnode); } }
private static bool GeneratePdf(string htmlText, string fileFullName, string watermarkText, PdfFont font) { if (string.IsNullOrEmpty(htmlText)) { return(false); } htmlText = "<p>" + htmlText + "</p>"; var document = new Document(); var writer = PdfWriter.GetInstance(document, new FileStream(fileFullName, FileMode.Create)); if (!string.IsNullOrEmpty(watermarkText)) { writer.PageEvent = new PdfWatermarkPageEvent(watermarkText); } document.Open(); //pipeline var htmlContext = new HtmlPipelineContext(null); htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory()); htmlContext.SetImageProvider(new ChannelImageProvider()); htmlContext.SetCssAppliers(new CssAppliersImpl(GetFontProviderBy(font))); var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true); var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer))); //parse byte[] data = Encoding.UTF8.GetBytes(htmlText); var msInput = new MemoryStream(data); var worker = new XMLWorker(pipeline, true); var parser = new XMLParser(worker); parser.Parse(msInput); //XMLWorkerHelper.GetInstance().ParseXHtml(..) var pdfDest = new PdfDestination(PdfDestination.XYZ, 0, document.PageSize.Height, 1f); var action = PdfAction.GotoLocalPage(1, pdfDest, writer); writer.SetOpenAction(action); //close document.Close(); msInput.Close(); return(true); }
public static void TestCreatePDF1() { try { Document document = new Document(); FileStream objFileStream = new System.IO.FileStream("Output.pdf", System.IO.FileMode.Create); PdfWriter writer = PdfWriter.GetInstance(document, objFileStream); document.Open(); document.AddDocListener(writer); PdfReader reader = new PdfReader("Input.pdf"); Document inputDocument = null; PdfCopy pdfCopyProvider = null; inputDocument = new Document(reader.GetPageSizeWithRotation(1)); pdfCopyProvider = new PdfCopy(inputDocument, objFileStream); inputDocument.Open(); PdfImportedPage importedPage = null; importedPage = pdfCopyProvider.GetImportedPage(reader, 1); pdfCopyProvider.Add(new Chunk("Chapter 1").SetLocalDestination("1")); pdfCopyProvider.AddPage(importedPage); // Code 2 PdfContentByte cb = writer.DirectContent; PdfOutline root = cb.RootOutline; // Code 3 PdfOutline oline1 = new PdfOutline(root, PdfAction.GotoLocalPage(1, new iTextSharp.text.pdf.PdfDestination(iTextSharp.text.pdf.PdfDestination.FITH), writer), "Chapter 1"); reader.Close(); //writer.Close(); inputDocument.Close(); //objFileStream.Close(); //document.Close(); } catch (Exception ex) { } }
public static Paragraph AddHypperLink(string name, int page, PdfWriter writer) { Chunk dottedLine = new Chunk(new DottedLineSeparator()); Chunk chunk = new Chunk(FontPolishChunk(name)); Chunk pageNumber = new Chunk($"{page}"); PdfAction action = PdfAction.GotoLocalPage(page, new PdfDestination(0), writer); chunk.SetAction(action); dottedLine.SetAction(action); pageNumber.SetAction(action); Paragraph pas = new Paragraph(chunk); pas.Add(dottedLine); pas.Add(pageNumber); return(pas); }
public void createPdf(String dest) { FileStream fs = new FileStream(dest, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); Document document = new Document(PageSize.LETTER); PdfWriter writer = PdfWriter.GetInstance(document, fs); document.Open(); TOCEvent evento = new TOCEvent(); writer.PageEvent = evento; for (int i = 0; i < 10; i++) { String title = "This is title " + i; Chunk c = new Chunk(title, new Font()); c.SetGenericTag(title); document.Add(new Paragraph(c)); for (int j = 0; j < 50; j++) { document.Add(new Paragraph("Line " + j + " of title " + i + " page: " + writer.PageNumber)); } } document.NewPage(); document.Add(new Paragraph("Table of Contents", new Font())); Chunk dottedLine = new Chunk(new DottedLineSeparator()); List <PageIndex> entries = evento.getTOC(); MultiColumnText columns = new MultiColumnText(); columns.AddRegularColumns(72, 72 * 7.5f, 24, 2); Paragraph p; for (int i = 0; i < 10; i++) { foreach (PageIndex pageIndex in entries) { Chunk chunk = new Chunk(pageIndex.Text); chunk.SetAction(PdfAction.GotoLocalPage(pageIndex.Name, false)); p = new Paragraph(chunk); p.Add(dottedLine); chunk = new Chunk(pageIndex.Page.ToString()); chunk.SetAction(PdfAction.GotoLocalPage(pageIndex.Name, false)); p.Add(chunk); columns.AddElement(p); } } document.Add(columns); document.Close(); }
private void PDFCombinePage(PdfOutline parent, Data.ONPage page) { if (page == null) { throw new ArgumentNullException("page"); } PdfReader reader = new PdfReader(page.PDFFilePath); Log.Information(string.Format("Import file {0}", page.PDFFilePath)); // we retrieve the total number of pages int n = reader.NumberOfPages; PdfContentByte cb = pdfWriter.DirectContent; PdfImportedPage impportPage; int rotation; int i = 0; while (i < n) { i++; pdfDocument.SetPageSize(reader.GetPageSizeWithRotation(i)); pdfDocument.NewPage(); impportPage = pdfWriter.GetImportedPage(reader, i); rotation = reader.GetPageRotation(i); if (rotation == 90 || rotation == 270) { cb.AddTemplate(impportPage, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height); } else { cb.AddTemplate(impportPage, 1f, 0, 0, 1f, 0, 0); } if (i == 1) { // set outline action at first page PdfAction action = PdfAction.GotoLocalPage(pdfWriter.CurrentPageNumber, new PdfDestination(PdfDestination.FITH, 806), pdfWriter); PdfOutline gotoPage = new PdfOutline(parent, action, page.Name); //TODO: fix this // pdfWriter.DirectContent.AddOutline(gotoPage,gotoPage.Title); } } pdfWriter.FreeReader(reader); }
/// <summary> /// Creates just the TOC page. /// </summary> /// <param name="inputPdf">The pdf to read from.</param> /// <param name="outputPdf">The toc pdf.</param> /// <param name="pageTOC">Page number for TOC page.</param> /// <param name="pageStart">The start of Contents for TOC.</param> /// <param name="pageEnd">The end of contents for TOC.</param> public static void CreateTOCPage(string inputPdf, string outputPdf, int pageTOC, int pageStart, int pageEnd) { //Bind a reader to our input file using (PdfReader reader = new PdfReader(inputPdf)) { using (FileStream fs = new FileStream(outputPdf, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)) { using (Document doc = new Document(reader.GetPageSizeWithRotation(1))) { PdfWriter writer = PdfWriter.GetInstance(doc, fs); doc.Open(); //Create the list of pageIndex manulally. List <PageIndex> toc = new List <PageIndex>(); for (int i = pageStart; i <= pageEnd; i++) { String text = GetContentsTextFromPage(inputPdf, i); toc.Add(new PageIndex() { Text = text, Name = "dest" + (i), Page = i }); } doc.NewPage(); Chunk dottedLine = new Chunk(new DottedLineSeparator()); Paragraph p; foreach (PageIndex pageIndex in toc) { Chunk chunk = new Chunk(pageIndex.Text); chunk.SetAction(PdfAction.GotoLocalPage(pageIndex.Name, false)); p = new Paragraph(chunk) { dottedLine }; chunk = new Chunk(pageIndex.Page.ToString()); chunk.SetAction(PdfAction.GotoLocalPage(pageIndex.Name, false)); p.Add(chunk); doc.Add(p); } } } } }
private void PDFCombineSection(PdfOutline parent, Data.ONSection section) { if (section == null) { throw new ArgumentNullException("section"); } if (section.Exclude) { return; } PdfOutline gotoPage = null; int currentPage = (pdfWriter.CurrentPageNumber == 1) ? pdfWriter.CurrentPageNumber : (pdfWriter.CurrentPageNumber + 1); PdfAction action = PdfAction.GotoLocalPage(currentPage, new PdfDestination(PdfDestination.FITH, 806), pdfWriter); gotoPage = new PdfOutline(parent, action, section.Name); pdfWriter.DirectContent.AddOutline(gotoPage); foreach (Data.ONSection subSection in section.SubSections) { if (!subSection.Exclude) { TOCHandler.AddTocEntry(subSection.Name, pdfWriter.CurrentPageNumber); TOCHandler.BeginTocEntry(); PDFCombineSection(gotoPage, subSection); TOCHandler.EndTocEntry(); } } foreach (Data.ONPage page in section.Pages) { if (pdfWriter.CurrentPageNumber == 1) { TOCHandler.AddTocEntry(page.Name, pdfWriter.CurrentPageNumber); } else { TOCHandler.AddTocEntry(page.Name, pdfWriter.CurrentPageNumber + 1); } PDFCombinePage(gotoPage, page); } }
// --------------------------------------------------------------------------- /** * Manipulates a PDF file src with the file dest as result (localhost) * @param src the original PDF */ public byte[] ManipulatePdf(byte[] src) { // Create the reader PdfReader reader = new PdfReader(src); int n = reader.NumberOfPages; using (MemoryStream ms = new MemoryStream()) { // Create the stamper using (PdfStamper stamper = new PdfStamper(reader, ms)) { // Get the writer (to add actions and annotations) PdfWriter writer = stamper.Writer; PdfAction action = PdfAction.GotoLocalPage(2, new PdfDestination(PdfDestination.FIT), writer ); writer.SetOpenAction(action); action = PdfAction.JavaScript( "app.alert('Think before you print');", writer ); writer.SetAdditionalAction(PdfWriter.WILL_PRINT, action); action = PdfAction.JavaScript( "app.alert('Think again next time!');", writer ); writer.SetAdditionalAction(PdfWriter.DID_PRINT, action); action = PdfAction.JavaScript( "app.alert('We hope you enjoy the festival');", writer ); writer.SetAdditionalAction(PdfWriter.DOCUMENT_CLOSE, action); action = PdfAction.JavaScript( "app.alert('This day is reserved for people with an accreditation " + "or an invitation.');", writer ); stamper.SetPageAction(PdfWriter.PAGE_OPEN, action, 1); action = PdfAction.JavaScript( "app.alert('You can buy tickets for all the other days');", writer ); stamper.SetPageAction(PdfWriter.PAGE_CLOSE, action, 1); } return(ms.ToArray()); } }
/// <summary> /// 将Html文字 输出到PDF档里 /// </summary> /// <param name="htmlText">html文本</param> /// <param name="param">pdf大小</param> /// <param name="waterMark">水印</param> /// <param name="stampPoint">模拟盖章</param> /// <returns></returns> public static byte[] ConvertHtmlTextToPdf(string htmlText, DocumentParam param, WatermarkSetting waterMark = null, StampPoint stampPoint = null) { if (string.IsNullOrEmpty(htmlText)) { return(null); } //避免当htmlText无任何html tag标签的纯文字时,转PDF时会挂掉,所以一律加上<p>标签 htmlText = "<p>" + htmlText + "</p>"; MemoryStream outputStream = new MemoryStream(); //要把PDF写到哪个串流 byte[] data = Encoding.UTF8.GetBytes(htmlText.ToCharArray()); //字串转成byte[] MemoryStream msInput = new MemoryStream(data); Document doc = new Document(param.PageSize, param.MarginLeft, param.MarginRight, param.MarginTop, param.MarginBottom);; //要写PDF的文件,建构子没填的话预设直式A4 PdfWriter writer = PdfWriter.GetInstance(doc, outputStream); //writer.SetViewerPreferences(PdfWriter.HideMenubar | PdfWriter.HideToolbar); //指定文件预设开档时的缩放为100% PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f); //开启Document文件 doc.Open(); if (stampPoint != null && !string.IsNullOrEmpty(stampPoint.Path)) { var img = Image.GetInstance(stampPoint.Path); img.SetAbsolutePosition(doc.PageSize.Width - img.Width - stampPoint.X, img.Height + stampPoint.Y); doc.Add(img); } //使用XMLWorkerHelper把Html parse到PDF档里 XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory()); //XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8); //将pdfDest设定的资料写到PDF档 var action = PdfAction.GotoLocalPage(1, pdfDest, writer); writer.SetOpenAction(action); doc.Close(); msInput.Close(); outputStream.Close(); return(SetWatermark(waterMark, outputStream.ToArray())); }
public string Print(List <string> labelList) { if (!Directory.Exists("out-labels-A4")) { Directory.CreateDirectory("out-labels-A4"); } labelList = AdjustCount(labelList); var outputPath = string.Format("{0}\\{1:dd_MM_yyyy_hh_mm_ss}.pdf", "out-labels-A4", DateTime.Now); Document document = new Document(PageSize.A4, 25, 25, 65, 0); var writer = PdfWriter.GetInstance(document, new FileStream(outputPath, FileMode.Create)); document.AddTitle("Barcode generator"); document.AddAuthor("Dipak Baba"); document.AddCreator("http://www.sangeetacollection.com"); document.Open(); PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, 0, 0.92f); PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer); writer.SetOpenAction(action); PdfPTable table = new PdfPTable(4); table.HorizontalAlignment = Element.ALIGN_LEFT; table.WidthPercentage = 100; table.DefaultCell.Border = Rectangle.NO_BORDER; foreach (var item in labelList) { table.AddCell(CreateImageCell(item)); } document.Add(table); document.Close(); return(outputPath); }
/// <summary> /// 将html转化为PDF的字节流 /// </summary> /// <param name="html">原始Html</param> /// <param name="message">转化信息</param> /// <returns>返回PDF的字节流</returns> public static byte[] FromHTMLtoPDF(string html, out string message) { Document document = new Document(); MemoryStream m = new MemoryStream(); MemoryStream stream = new MemoryStream(); byte[] bytes = null; try { PdfWriter writer = PdfWriter.GetInstance(document, m); document.Open(); PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, document.PageSize.Height, 1f); Encoding charset = Encoding.GetEncoding("gb2312"); byte[] data = charset.GetBytes(html); stream.Write(data, 0, data.Length); stream.Position = 0; XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, stream, null, charset, new UnicodeFontFactory()); PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer); writer.SetOpenAction(action); document.Close(); bytes = m.GetBuffer(); message = "100|成功"; } catch (Exception e) { string err = "Invalid nested tag body found"; if (e.Message.Contains(err)) { message = "102|html元素没有闭合标签"; } else { message = "102|将html转换为pdf出错!"; } } finally { stream.Close(); m.Close(); } return(bytes); }
public byte[] ConvertHtmlTextToPDF(string htmlText, string styleCss) { if (string.IsNullOrEmpty(htmlText)) { return(null); } //避免当htmlText无任何html tag标签的纯文字时,转PDF时会挂掉,所以一律加上<p>标签 htmlText = "<p>" + htmlText + "</p>"; MemoryStream outputStream = new MemoryStream(); //要把PDF写到哪个串流 byte[] data = Encoding.UTF8.GetBytes(htmlText); //字串转成byte[] MemoryStream msInput = new MemoryStream(data); byte[] dataCss = Encoding.UTF8.GetBytes(styleCss);//字串转成byte[] MemoryStream cssStream = new MemoryStream(dataCss); Document doc = new Document();//要写PDF的文件,建构子没填的话预设直式A4 PdfWriter writer = PdfWriter.GetInstance(doc, outputStream); PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f); //开启Document文件 doc.Open(); //HeaderAndFooterEvent header = new HeaderAndFooterEvent(); //header.tpl = writer.DirectContent.CreateTemplate(100, 100); //writer.PageEvent = header; //使用XMLWorkerHelper把Html parse到PDF档里 XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, cssStream, Encoding.UTF8, new UnicodeFontFactory()); //将pdfDest设定的资料写到PDF档 PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer); writer.SetOpenAction(action); doc.Close(); msInput.Close(); cssStream.Close(); outputStream.Close(); //回传PDF档案 return(outputStream.ToArray()); }
private static PdfPTable GenerateTableOfContents(PdfEvents tocEvent, PdfStamper stamper, int tocSize) { var tableOfContents = new PdfPTable(2); tableOfContents.SetWidths(new[] { 10, 1 }); tableOfContents.WidthPercentage = 100; tableOfContents.DefaultCell.Border = Rectangle.NO_BORDER; foreach (var item in tocEvent.Toc) { tableOfContents.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; tableOfContents.DefaultCell.PaddingLeft = 10 * (item.Level - 1); Font font; if (item.Level == 0) { tableOfContents.DefaultCell.PaddingBottom = 10; tableOfContents.DefaultCell.PaddingTop = 10; font = PdfFonts.Bold; } else { tableOfContents.DefaultCell.PaddingBottom = 2; tableOfContents.DefaultCell.PaddingTop = 2; font = PdfFonts.Normal; } var chunk = new Chunk(item.Title, font); var action = PdfAction.GotoLocalPage(item.Page, new PdfDestination(PdfDestination.FIT), stamper.Writer); chunk.SetAction(action); tableOfContents.AddCell(new Phrase(chunk)); tableOfContents.DefaultCell.PaddingLeft = 0; tableOfContents.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT; chunk = new Chunk(string.Format("{0}", item.Page + tocSize), font); tableOfContents.AddCell(new Phrase(chunk)); } return(tableOfContents); }
/// <summary> /// 將Html文字 輸出到PDF檔裡 /// </summary> /// <param name="Html"></param> /// <returns></returns> public byte[] ToPdf(string Html) { if (string.IsNullOrEmpty(Html)) { return(null); } //避免當htmlText無任何html tag標籤的純文字時,轉PDF時會掛掉,所以一律加上<p>標籤 //Html = "<p>" + Html + "</p>"; try { using (MemoryStream outputStream = new MemoryStream()) //要把PDF寫到哪個串流 { byte[] data = Encoding.UTF8.GetBytes(Html); //字串轉成byte[] using (MemoryStream msInput = new MemoryStream(data)) { using (Document doc = new Document())//要寫PDF的文件,建構子沒填的話預設直式A4 { PdfWriter writer = PdfWriter.GetInstance(doc, outputStream); //指定文件預設開檔時的縮放為100% PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f); //開啟Document文件 doc.Open(); //使用XMLWorkerHelper把Html parse到PDF檔裡 XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory()); //將pdfDest設定的資料寫到PDF檔 PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer); writer.SetOpenAction(action); } } //回傳PDF檔案 return(outputStream.ToArray()); } } catch (Exception e) { throw new Exception("Html Transform Pdf Fail!!!", e); } }