以适当的格式生成PDF文件

时间:2013-08-30 17:09:11

标签: java servlets flying-saucer htmlcleaner

对于我的使用,我使用飞碟库创建了一个PDF文件。这是一个遗留HTML,所以我使用HTMLCleaner库清理了XHTML。

在此之后,我将XML序列化为字符串,然后将其传递给fly-saucer的iText模块进行渲染,然后创建PDF。

此PDF我将其放在OutputStream中。提交响应后,我会收到一个对话框,要求保存或打开它。但是它不会保存为PDF文件。我必须右键单击并在Adobe或任何PDF阅读器中打开它。

如何在PDF阅读器中显示它。并将文件保存为.pdf文件。什么是一个有效和用户友好的方式来处理这个问题?一如既往的帮助将不胜感激!

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringBufferInputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.DomSerializer;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.PrettyXmlSerializer;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XmlSerializer;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xhtmlrenderer.resource.XMLResource;

public class MyPDF extends HttpServlet {


public MyPDF() {
    super();
}


public void destroy() {
    super.destroy(); 
}


public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    doPost(request, response);
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/pdf");

    String html = request.getParameter("source");

    try 
    {
        HtmlCleaner cleaner = new HtmlCleaner();
        CleanerProperties props = cleaner.getProperties();

        TagNode node = cleaner.clean(html);

        //String content = "<" + node.getName() + ">" + cleaner.getInnerHtml(node) + "</" + node.getName() + ">";
        //System.out.println("content " +content);

        OutputStream os = response.getOutputStream();
        System.out.println("encoding " +response.getCharacterEncoding());

        final XmlSerializer xmlSerializer = new PrettyXmlSerializer(props);
        final String html1 = xmlSerializer.getAsString(node);

        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(html1);
        renderer.layout();

        renderer.createPDF(os);
        os.close();
    } 
    catch (Exception ex) 
    {
        ex.printStackTrace();
    }


}


public void init() throws ServletException {

}

}

1 个答案:

答案 0 :(得分:1)

您的MIME类型对于PDF不正确。它应该是application / pdf。

更改

response.setContentType("text/pdf");

response.setContentType("application/pdf");

有关PDF MIME类型的RFC,请参阅http://tools.ietf.org/html/rfc3778

编辑:完全忽略了“另存为.pdf”问题。 您还需要添加以下内容:

response.setHeader("content-disposition", "attachment; filename=yourFileName.pdf");

告诉浏览器默认文件名应该是什么。