A few days ago the project involves the download function of PDF, after a few days of effort has been completed, deliberately will be involved in a summary of the things.
The project is related to several jar packages: itextpdf5.5.6,xmlworker5.5.6,itext-asian5.2.0 (the Linux server cannot display the Chinese must this package, Windows Server does not need), these three packages can be fully
Made in Maven repository.
Directly on the code:
One
String path =servletactioncontext.getservletcontext (). Getrealpath ("/");
String HTML = path+ "A.sql";
Path note differences between Linux and Windows backslashes
HttpServletResponse response= servletactioncontext.getresponse ();
OutputStream outputstream = Response.getoutputstream ();
Response.setcontenttype ("Application/pdf");
String pdfname = "Download locally. pdf";
Response.AddHeader ("Content-disposition", "attachment;filename=" + New String (Pdfname.getbytes ("gb2312"), " Iso-8859-1 "));
Document document = new document ();
Here with OutputStream is made into the flow of the style, if only download to the local, just replace the cost of file add address to
PDFWriter writer = pdfwriter.getinstance (document, OutputStream);
Document.open ();
This method can be seen in the Xmlworkerhelper API documentation, there is a detailed introduction, Chinafont is a custom Chinese class, mainly to solve the Linux server under the Chinese can not display problems
Methods 1 and 2 are selected as needed
1, Xmlworkerhelper.getinstance (). parsexhtml (writer, document, new FileInputStream (HTML),
Null,charset.forname ("UTF-8"), New Chinafont ());
If Windows Server is optional in the following method, you do not need to define your own Chinese class
2. xmlworkerhelper.parsexhtml (writer, document,
New FileInputStream (HTML), Charset.forname ("UTF-8"));
Document.close ();
Outputstream.flush ();
Second, the custom Chinese class
This class must implement the Fontprovider interface
public class Chinafont implements Fontprovider {
@Override
public boolean isregistered (String fontname) {
return false;
}
Public Font GetFont (string fontname, String encoding, Boolean embedded, float size, int style, Basecolor color) {
try {
Basefont Bfchinese;
Bfchinese = Basefont.createfont ("Stsong-light", "unigb-ucs2-h", basefont.not_embedded);
return new Font (Bfchinese, size, style, color);
} catch (Documentexception e) {
E.printstacktrace ();
} catch (IOException e) {
E.printstacktrace ();
}
return null;
}
The IText plugin downloads the page as an output stream in PDF format