为我用,我创建使用的飞碟库中的PDF文件。 这是一个传统的HTML,所以我清理使用HTMLCleaner库XHTML。
此后,我序列化XML作为字符串,然后把它传递给飞碟的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 {
}
}