English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Implementation Method of Dynamic JSP Page to PDF Conversion and Output to Page

I have encountered many problems in recent work. Summarize them. The main function of this code is to forward a generated JSP page to PDF output on the page

It needs to use ITEXT

String html = ServletUtils.forward(request,response,"/WEB-INF/jsp/depot/print/jhd.jsp"); //Forward the request to jsp and return the parsed content instead of outputting to the browser
//System.out.println(html);
byte[] pdf = PDFUtils.html2pdf(html);
response.setContentType("application/pdf");
response.setHeader("Content-Length",String.valueOf(pdf.length));
response.setHeader("Connection","keep-alive");
response.setHeader("Accept-Ranges","none");
response.setHeader("X-Frame-Options","DENY");
OutputStream out = response.getOutputStream();
out.write(pdf);
out.flush();
public class ServletUtils {
/**
* This forward method does not output content to the browser after execution, but outputs to the byte stream and finally returns as a string
* @param request
* @param response
* @param src
* @return
*/
public static String forward(HttpServletRequest request, HttpServletResponse response, String src) {
try{
/* ↓↓↓↓↓Reconstruct response and modify the output stream object in response to output to a byte array↓↓↓↓↓ */
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final ServletOutputStream servletOutputStream = new ServletOutputStream() {
@Override
public void write(int b) throws IOException {
byteArrayOutputStream.write(b);
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setWriteListener(WriteListener writeListener) {
}
};
final PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(byteArrayOutputStream, "UTF-8"));-8"));
response = new HttpServletResponseWrapper(response) {
public ServletOutputStream getOutputStream() {
return servletOutputStream;
}
public PrintWriter getWriter() {
return printWriter;
}
};
/* ↑↑↑↑↑↑Reconstruct response and modify the output stream object in response to output to a byte array↑↑↑↑↑↑ */
//Perform the forward operation
request.getRequestDispatcher(src).forward(request, response);
//Convert the content in the byte stream to a string
return new String(byteArrayOutputStream.toByteArray(),"utf-8");-8");
}
catch (Exception e){
throw new RuntimeException(e);
}
}
}
import com.itextpdf.text.*;*;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.Pipeline;
import com.itextpdf.tool.xml.XMLWorker;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.tool.xml.exceptions.CssResolverException;
import com.itextpdf.tool.xml.html.CssAppliers;
import com.itextpdf.tool.xml.html.CssAppliersImpl;
import com.itextpdf.tool.xml.html.Tags;
import com.itextpdf.tool.xml.parser.XMLParser;
import com.itextpdf.tool.xml.pipeline.css.CSSResolver;
import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
import com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;
import java.io.*;*;
/**
* pdf utility class
*/
public class PDFUtils {
/**
* Convert html to pdf and return the pdf file in the form of a byte array
* @param html
* @return pdf byte array
* @throws IOException
* @throws DocumentException
* @throws CssResolverException
*/
public static byte[] html2pdf(String html) throws IOException, DocumentException,CssResolverException {
Document document = new Document(PageSize.A4);
ByteArrayOutputStream os = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document,os);
document.open();
XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(){
@Override
public Font getFont(String fontname, String encoding, float size, int style) {
return super.getFont(fontname == null ? "Songti" : fontname, encoding, size, style);
}
};
fontProvider.addFontSubstitute("lowagie", "garamond");
fontProvider.setUseUnicode(true);
//Using our font provider and setting it as unicode font style
CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
CSSResolver cssResolver = XMLWorkerHelper.getInstance().getDefaultCssResolver(true);
Pipeline<?> pipeline = new CssResolverPipeline(cssResolver,new HtmlPipeline(htmlContext, new PdfWriterPipeline(document,writer)));
XMLWorker worker = new XMLWorker(pipeline, true);
XMLParser p = new XMLParser(worker);
p.parse(new InputStreamReader(new ByteArrayInputStream(html.getBytes("gbk"))));
document.close();
return os.toByteArray();
}
}

The above-mentioned is the method introduced by the editor to implement the dynamic jsp page conversion to PDF output to the page, hoping it will be helpful to everyone. If you have any questions, please leave a message, and the editor will reply to everyone in time!

Declaration: The content of this article is from the Internet, the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal responsibility. If you find any content suspected of copyright infringement, please send an email to notice#w.3Please report via email to codebox.com (replace # with @ when sending an email) and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.

You May Also Like