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.
- import com.itextpdf.text.*;
- import Com.itextpdf.text.pdf.BaseFont;
- import Com.itextpdf.text.pdf.PdfWriter;
- import Com.itextpdf.tool.xml.XMLWorkerHelper;
- import Org.jsoup.Jsoup;
- import Java.io.ByteArrayInputStream;
- import Java.io.FileOutputStream;
- import Java.io.InputStream;
- /**
- * Created by Sinoprof Codeproducer
- * User:ck
- * date:2017-10-31
- * time:09:25:06
- * Implement generate PDF file
- */
- public class createpdfdocument {
- /**
- * Based on the basic information of the URL advance blog, return the results
- * @param URL Example: http://localhost:8080/scm/scm/po/gather/pdftest/pdftesthtml3.html (the URL that can return an HTML directly,
- * 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)
- * @return
- * @throws Exception
- */
- public Static string[] Extracthtmlinfo (String URL) throws Exception {
- / * Why do you use arrays here, because you can return not only the selected HTML,
- 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 * *
- String[] Info = new string[1];
- //Parse URL directly into document, then call Document.html () to parse to HTML
- Org.jsoup.nodes.Document doc = Jsoup.connect (URL). get ();
- //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
- Org.jsoup.nodes.Element entry = Doc.select ("Div.entry"). First ();
- info[0] = entry.html ();
- return info;
- }
- /**
- * Get the desired portion of HTML directly by getting HTML
- * @param html
- * @return
- * @throws Exception
- */
- public Static string[] ExtractHtmlInfo2 (String html) throws Exception {
- String[] Info = new string[1];
- //Convert HTML to document
- Org.jsoup.nodes.Document doc = jsoup.parse (HTML);
- //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
- Org.jsoup.nodes.Element entry = Doc.select ("Div.entry"). First ();
- info[0] = entry.html ();
- return info;
- }
- /**
- * Convert string to InputStream
- * @param content
- * @return
- */
- Public static InputStream parse2stream(String content) {
- try {
- Bytearrayinputstream stream = new Bytearrayinputstream (
- Content.getbytes ("GBK"));
- return stream;
- } catch (Exception e) {
- return null;
- }
- }
- /**
- * Convert Web content directly into PDF file
- *
- * @param
- * @throws Exception
- */
- Public static string parseurl2pdffile(string pdffile, string html) {
- String returnval = "";
- try {
- Basefont BFCN = Basefont.createfont ("Stsongstd-light", "Unigb-ucs2-h",
- false);
- //Chinese font definition
- Font chFont = new Font (BFCN, + , Font.normal, basecolor.blue);
- Font secfont = new Font (BFCN, font.normal, new Basecolor (0, 204,
- 255));
- Font textfont = new Font (BFCN, font.normal, basecolor.black);
- Document document = New document (PAGESIZE.A4);
- //Set background image for PDF
- Image image = Image.getinstance ("d:/moving background picture. jpg");
- Image.setalignment (image. underlying);
- Image.setabsoluteposition (0,0);
- Image.scaleabsolute (595,842);
- PDFWriter PDFWriter = pdfwriter.getinstance (document,
- new FileOutputStream (Pdffile));
- Pdfwriter.setviewerpreferences (Pdfwriter.hidetoolbar);
- Document.open ();
- Document.add (image);
- //Get parsed HTML
- string[] Bloginfo = ExtractHtmlInfo2 (HTML);
- convert/*html files to PDF documents
- the Asianfontprovider () function is used to resolve xmlworkerhelper.getinstance (). parsexhtml () to PDF Chinese does not display the problem */
- Xmlworkerhelper.getinstance (). parsexhtml (PDFWriter, Document,parse2stream (bloginfo[0]),null, new Asianfontprovider ());
- Document.close ();
- ReturnVal = "YES";
- } catch (Exception e) {
- ReturnVal = "NO";
- E.printstacktrace ();
- } finally {
- return returnval;
- }
- }
- }
- import Com.itextpdf.text.BaseColor;
- import Com.itextpdf.text.Font;
- import Com.itextpdf.text.pdf.BaseFont;
- import Com.itextpdf.tool.xml.XMLWorkerFontProvider;
- /**
- * Created by Sinoprof Codeproducer
- * User:ck
- * date:2017-10-31
- * time:09:25:06
- * Used to resolve xmlworkerhelper.getinstance (). parsexhtml () to PDF Chinese does not display problems
- */
- public class Asianfontprovider extends xmlworkerfontprovider{
- Public Font getfont(final string fontname, final string encoding,
- Final boolean embedded, final float size, final int style,
- final Basecolor color) {
- Basefont BF = null;
- try {
- BF = Basefont.createfont ("Stsong-light", "Unigb-ucs2-h", basefont.not_embedded);
- } catch (Exception e) {
- E.printstacktrace ();
- }
- Font font = new Font (BF, size, style, color);
- Font.setcolor (color);
- return font;
- }
- }
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