Automatically generate PDF documents for dynamic JSP pages (or static HTML) and upload them to the server

Source: Internet
Author: User
Tags set background url example

pinned November 06, 2017 14:41:04 Hits: 2311

These days, the task has a difficulty is to automatically generate a print page PDF document, and upload to the server, but the company framework only manually upload documents, printing can be saved as a PDF local bar, so feel very headache, just start without direction, so only surf the internet, Online read a lot of information, gradually from a little direction also do not understand, to slowly begin to understand how to do, nonsense will not say,

I think the online introduction of three ways: Jasper report, IText, flying Sauser

Jasper report and Flying Sauser feel more powerful than the itext implementation, but I do not have much need for CSS, because it is a very simple form, (if the style of the PDF is very high requirements, you can go to see flying Sauser, this thing can parse HTML and CSS, and can output to image,pdf and other formats), I use is itext, I use the jar is:

itext-asian-5.2.0, itextpdf-5.5.1, xmlworker-5.5.4, jsoup-1.10.2 (this package is the HTML parser for Java)

1. Automatically generate PDF,

The following Createpdfdocument.java, Asianfontprovider.java is two tool classes, Asianfontprovider is called in the Createpdfdocument, The createpdfdocument will be called in a later implementation.

  1. import com.itextpdf.text.*;
  2. import Com.itextpdf.text.pdf.BaseFont;
  3. import Com.itextpdf.text.pdf.PdfWriter;
  4. import Com.itextpdf.tool.xml.XMLWorkerHelper;
  5. import Org.jsoup.Jsoup;
  6. import Java.io.ByteArrayInputStream;
  7. import Java.io.FileOutputStream;
  8. import Java.io.InputStream;
  9. /**
  10. * Created by Sinoprof Codeproducer
  11. * User:ck
  12. * date:2017-10-31
  13. * time:09:25:06
  14. * Implement generate PDF file
  15. */
  16. public class createpdfdocument {
  17. /**
  18. * Based on the basic information of the URL advance blog, return the results
  19. * @param URL Example: http://localhost:8080/scm/scm/po/gather/pdftest/pdftesthtml3.html (the URL that can return an HTML directly,
  20. * I started to pass the URL when the Struts1 intercept, should be get not to the session of the login information, so get the login page html)
  21. * @return
  22. * @throws Exception
  23. */
  24. public Static string[] Extracthtmlinfo (String URL) throws Exception {
  25. / * Why do you use arrays here, because you can return not only the selected HTML,
  26. There is also a separate array of information extracted from the document to return, and then use Itext in the PDF to assemble the data, you can check online * *
  27. String[] Info = new string[1];
  28. //Parse URL directly into document, then call Document.html () to parse to HTML
  29. Org.jsoup.nodes.Document doc = Jsoup.connect (URL). get ();
  30. //This doc.select is used to select a part of the complete HTML here for the first div of the CSS is entry, so you have a div on the HTML class for entry Oh
  31. Org.jsoup.nodes.Element entry = Doc.select ("Div.entry"). First ();
  32. info[0] = entry.html ();
  33. return info;
  34. }
  35. /**
  36. * Get the desired portion of HTML directly by getting HTML
  37. * @param html
  38. * @return
  39. * @throws Exception
  40. */
  41. public Static string[] ExtractHtmlInfo2 (String html) throws Exception {
  42. String[] Info = new string[1];
  43. //Convert HTML to document
  44. Org.jsoup.nodes.Document doc = jsoup.parse (HTML);
  45. //This doc.select is used to select a part of the complete HTML here for the first div of the CSS is entry, so you have a div on the HTML class for entry Oh
  46. Org.jsoup.nodes.Element entry = Doc.select ("Div.entry"). First ();
  47. info[0] = entry.html ();
  48. return info;
  49. }
  50. /**
  51. * Convert string to InputStream
  52. * @param content
  53. * @return
  54. */
  55. Public static InputStream parse2stream(String content) {
  56. try {
  57. Bytearrayinputstream stream = new Bytearrayinputstream (
  58. Content.getbytes ("GBK"));
  59. return stream;
  60. } catch (Exception e) {
  61. return null;
  62. }
  63. }
  64. /**
  65. * Convert Web content directly into PDF file
  66. *
  67. * @param
  68. * @throws Exception
  69. */
  70. Public static string parseurl2pdffile(string pdffile, string html) {
  71. String returnval = "";
  72. try {
  73. Basefont BFCN = Basefont.createfont ("Stsongstd-light", "Unigb-ucs2-h",
  74. false);
  75. //Chinese font definition
  76. Font chFont = new Font (BFCN, + , Font.normal, basecolor.blue);
  77. Font secfont = new Font (BFCN, font.normal, new Basecolor (0, 204,
  78. 255));
  79. Font textfont = new Font (BFCN, font.normal, basecolor.black);
  80. Document document = New document (PAGESIZE.A4);
  81. //Set background image for PDF
  82. Image image = Image.getinstance ("d:/moving background picture. jpg");
  83. Image.setalignment (image. underlying);
  84. Image.setabsoluteposition (0,0);
  85. Image.scaleabsolute (595,842);
  86. PDFWriter PDFWriter = pdfwriter.getinstance (document,
  87. new FileOutputStream (Pdffile));
  88. Pdfwriter.setviewerpreferences (Pdfwriter.hidetoolbar);
  89. Document.open ();
  90. Document.add (image);
  91. //Get parsed HTML
  92. string[] Bloginfo = ExtractHtmlInfo2 (HTML);
  93. convert/*html files to PDF documents
  94. the Asianfontprovider () function is used to resolve xmlworkerhelper.getinstance (). parsexhtml () to PDF Chinese does not display the problem */
  95. Xmlworkerhelper.getinstance (). parsexhtml (PDFWriter, Document,parse2stream (bloginfo[0]),null, new Asianfontprovider ());
  96. Document.close ();
  97. ReturnVal = "YES";
  98. } catch (Exception e) {
  99. ReturnVal = "NO";
  100. E.printstacktrace ();
  101. } finally {
  102. return returnval;
  103. }
  104. }
  105. }
  1. import Com.itextpdf.text.BaseColor;
  2. import Com.itextpdf.text.Font;
  3. import Com.itextpdf.text.pdf.BaseFont;
  4. import Com.itextpdf.tool.xml.XMLWorkerFontProvider;
  5. /**
  6. * Created by Sinoprof Codeproducer
  7. * User:ck
  8. * date:2017-10-31
  9. * time:09:25:06
  10. * Used to resolve xmlworkerhelper.getinstance (). parsexhtml () to PDF Chinese does not display problems
  11. */
  12. public class Asianfontprovider extends xmlworkerfontprovider{
  13. Public Font getfont(final string fontname, final string encoding,
  14. Final boolean embedded, final float size, final int style,
  15. final Basecolor color) {
  16. Basefont BF = null;
  17. try {
  18. BF = Basefont.createfont ("Stsong-light", "Unigb-ucs2-h", basefont.not_embedded);
  19. } catch (Exception e) {
  20. E.printstacktrace ();
  21. }
  22. Font font = new Font (BF, size, style, color);
  23. Font.setcolor (color);
  24. return font;
  25. }
  26. }



The following call to generate a PDF, I just write a main method, take care not to directly reference the following code oh, this is two cases, choose one to try
/** * @paramargs*/public static void Main (string[] args) throws Exception {// the Web page must be directly accessibleURL,String Blogurl = "http://localhost:8080/scm/scm/po/gather/pdftest/pdftesthtml3.html";// Pass in your ownHTML,NoteHTMLto meet thethe standardHTML, becauseItexttheHTMLThe format is a bit strict,String html = "";//PDFthe final output document, noteD:/test/itextthesefolderwe have to build it first.String pdffile = "D:/test/itext/demo-url.pdf";// Direct Web content toPDFfile But this page must be accessible directlyURL,Note that inCreatepdfdocument.javaof theParseurl2pdffilemethod to invoke theExtracthtmlinfoMethodDemo4url2pdf.parseurl2pdffile (Pdffile, Blogurl);// Direct IncomingHTML, pay attention to theCreatepdfdocument.javaparseurl2pdffilemethod to invoke theExtractHtmlInfo2MethodDemo4url2pdf.parseurl2pdffile (pdffile, HTML);}

This will basically be able to generate a PDF document in the location you specify, but note that Itext has little support for HTML styling, so the resulting PDF document is relatively simple, jtext-asian-5.2.0, itextpdf-5.5.1, xmlworker-5.5.4, these three jars are my support for the table tag on the Internet, (the lower version of the jar I started looking for doesn't support table, so my form doesn't come out), There is asianfontprovider.java this kind of support for Chinese, because Itext xmlworkerhelper. GetInstance(). When parsexhtml to PDF, the Chinese does not display,

(Online said is what does not have the default Chinese font, I see online someone modifies Xmlworker source code, make its default a font),

But I didn't succeed, and I found this without modifying the source code, just like this.

Xmlworkerhelper. GetInstance(). Parsexhtml(pdfwriter,document,parse2stream(bloginfo[0]), null,newAsianfontprovider());

Just can help me to solve my needs, the result picture is as follows:


The following talk about the difficulties encountered in the task, said that the automatic generation of PDFs can be directly passed to the string type of HTML or URL, but this URL if the class can be directly accessed, such as the Web site URL, but our project has struts1 will intercept no landing, No login will jump to the login page, so every time I use the URL to test, the return is always a login page HTML, in fact, I need a dynamic JSP generated PDF.

Just, let me find out a ready-made method, in fact, the principle is: to get the data, so that the JSP page does not lose in the browser display, but output to the last word stream in the form of characters to return, so I can get the dynamic JSP assembly and output of the static HTML, so that I want to get the HTML.

Specifically I direct PO blogger's blog Bar http://www.cnblogs.com/Iran1112/p/6013474.html, which I learned how to let dynamic JSP output HTML in a streaming way.

As for uploading to the server, to see how their servers to store, the general idea: Read and write files such as this:

input Stream FileInputStream fi = new FileInputStream (Fpath); Bufferedinputstream bi = new Bufferedinputstream (FI);  output stream fileoutputstream fo = new FileOutputStream (newFile); Bufferedoutputstream bo = new Bufferedoutputstream (FO);  Define a byte buffer, reduce I/O times, improve read and write efficiency byte[] buf = new Byte[1024];int len = 0;while (len= Bi.read (BUF))!=-1) {    bo.write (buf,0,len);     so that the buffered output bytes are written to the underlying output stream to avoid computer power loss and other special circumstances, causing the data in the buffer to be emptied bo.flush ();} Fi.close (); Fo.close ();
Then get the file information, such as: file name, storage path, size ..., and then insert (deposit) in their own table, basically this is probably the case.

Automatically generate PDF documents for dynamic JSP pages (or static HTML) and upload them to the server

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.