如何使用iText生成PDF时摆脱异常

时间:2012-01-25 23:48:09

标签: java spring-mvc pdf-generation itext

我试图在java spring framework mvc中使用itext渲染pdf。 这是我的过滤器类。

 public class PdfFilter implements Filter, ApplicationContextAware {

@SuppressWarnings({ "UnusedDeclaration" })
private static final Logger log = Logger.getLogger(PdfFilter.class);
protected ApplicationContext applicationContext;

public void init(FilterConfig config) {
    /* do nothing */
}

public void destroy() {
    /* do nothing */
}

public void doFilter(ServletRequest req, ServletResponse resp,
        FilterChain filterChain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;

    // Check to see if this filter should apply.
    if (!"pdf".equals(request.getParameter("reportViewType"))) {
        filterChain.doFilter(request, response);
        return;
    }

    // Capture the content for this request
    ContentCaptureServletResponse capContent = new ContentCaptureServletResponse(
            response);
    filterChain.doFilter(request, capContent);

    response.setContentType("application/pdf; charset=UTF-8");
    response.setHeader("Content-disposition",
            "attachment; filename=\"report.pdf\"");
    response.addHeader("Cache-Control", "-1");

    try {
        // Get the html content
        String htmlContent = capContent.getHtlmContent();

        PdfGenerator pdfGenerator = new PdfGenerator(
                response.getOutputStream());

        pdfGenerator.renderPdf(htmlContent, request, response);

    } catch (Exception e) {
        throw new ServletException(e);
    }
}

public void setApplicationContext(ApplicationContext applicationContext) {
    this.applicationContext = applicationContext;
}
}

这是我的pdfGenerator类     公共类PdfGenerator {     private static final Logger log = Logger.getLogger(PdfGenerator.class);     private OutputStream outputStream;

public PdfGenerator(OutputStream os) {
    this.outputStream = os;
}

public void renderPdf(String htmlContent, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    log.debug("renderPdf");

    htmlContent = cleanUpHtml(htmlContent);
    htmlContent = addHeadBodyTag(htmlContent);

    htmlContent = addCss(htmlContent);

    log.debug("convertToXhtml-e:");
    OutputStream xhtmlOs = new ByteArrayOutputStream();

    Tidy tidy = new Tidy();
    tidy.setXHTML(true);
    tidy.setCharEncoding(Configuration.UTF8);
    tidy.parse(new ByteArrayInputStream(htmlContent.getBytes()), xhtmlOs);

    xhtmlOs.flush();
    xhtmlOs.close();
    log.debug(xhtmlOs.toString());
    StringReader contentReader = new StringReader(xhtmlOs.toString());

    InputSource source = new InputSource(contentReader);

    DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder();
    // documentBuilder.setEntityResolver(new MyResolver(request));
    documentBuilder.setEntityResolver(new NoOpEntityResolver());

    Document xhtmlContent = documentBuilder.parse(source);

    ITextRenderer renderer = new ITextRenderer();
    renderer.setDocument(xhtmlContent, null);
    renderer.layout();

    renderer.createPDF(outputStream);

    outputStream.close();

}

private String cleanUpHtml(String data) {
    log.debug("cleanUpHtml-e:");

    data = HtmlUtils.removeAllTags(data, "<script", "</script>", null);
    data = HtmlUtils.replaceAll(data, "<a .*?>|</a>", "");
    // data = HtmlUtils.replaceAll(data, "<img .*?>|</img>", "");
    data = HtmlUtils.replaceAll(data, "<link .*?>", "");
    // remove hidden field
    data = HtmlUtils.replaceAll(data, "<input.*?type=['\"]hidden['\"].*?>",
            "");
    // remove pagination from lister
    data = HtmlUtils
            .replaceAll(
                    data,
                    "(<div style=\"top: .*?px; position: absolute;\" id=\"pager\" class=\"pager\".*?</div>)",
                    "");

    return data;
}

private String addHeadBodyTag(String data) {
    // data = "<html><head></head><body>" + data + "</body></html>";
    return data;
}

private String addCss(String data) {
    log.debug("addCss-e:");

    return data;
}

private String addHead(String data, HttpServletRequest request) {
    log.debug("addHeader-e:");
    StringBuilder sb = new StringBuilder(500);
    String header = sb.toString();
    data = HtmlUtils.replaceAll(data, "(<body.*?>)", "$1" + header);

    return data;

}

private String addFooter(String data) {
    log.debug("addFooter-e:");

    String footer = "iit lone gunmen 2.0";

    data = HtmlUtils.replaceAll(data, "(<body.*?>)", "$1" + footer);
    return data;
}

}

但不知怎的,我得到了一些例外:

 Jan 26, 2012 5:43:08 AM org.apache.catalina.core.StandardWrapperValve invoke
 SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/govForms]       threw exception [Filter execution threw an exception] with root cause
    java.lang.NoSuchMethodError: com.lowagie.text.Rectangle.getHeight()F
at org.xhtmlrenderer.pdf.ITextRenderer.writePDF(ITextRenderer.java:339)
at org.xhtmlrenderer.pdf.ITextRenderer.createPDF(ITextRenderer.java:315)
at org.xhtmlrenderer.pdf.ITextRenderer.createPDF(ITextRenderer.java:246)
at bd.gov.forms.web.pdf.PdfGenerator.renderPdf(PdfGenerator.java:64)
at bd.gov.forms.web.pdf.PdfFilter.doFilter(PdfFilter.java:54)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.opensymphony.module.sitemesh.filter.PageFilter.parsePage(PageFilter.java:119)
at com.opensymphony.module.sitemesh.filter.PageFilter.doFilter(PageFilter.java:55)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

感谢任何形式的帮助。 感谢。

2 个答案:

答案 0 :(得分:0)

NoSuchMethod错误表明您使用的库版本不匹配。我将首先检查我的库依赖项,并找出是否有些库不期望不同版本的iText。如果是这样,我会尝试排除一个依赖项或选择支持适当版本iText的库版本。

如果你正在使用Maven,请尝试:mvn dependency:tree并检查多个iText出现

答案 1 :(得分:-1)

PDF生成过程可能由于各种原因而失败。 您必须在try / catch块中包围pdf生成,并在catch块中进行某种错误处理。我看到了解决这个问题的两种基本方法:

  1. 使用默认的pdf文档部署您的应用:在catched generation exception中提供默认pdf的内容,其中包含失败代的通用警告短语
  2. pdf生成器以字节流的形式返回结果(而不是直接在响应输出流中),并且只有在正确返回时,才设置响应头以提供生成的pdf并复制响应输出中返回的字节流;在catched generation exception中,您设置响应以提供描述错误的html页面,或者您可以重定向到标准错误页面。