2013-08-30 56 views
0

對於我的使用,我使用飛碟庫創建了一個PDF文件。這是一個遺留的HTML,所以我使用HTMLCleaner庫清理了XHTML。以適當的格式生成PDF文件

之後,我將XML作爲字符串序列化,然後將其傳遞給飛碟的iText模塊以呈現它並隨後創建PDF。

This 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

您的MIME類型型號不適合PDF格式。它應該是應用程序/ pdf。

變化

response.setContentType("text/pdf"); 

response.setContentType("application/pdf"); 

爲RFC爲PDF MIME類型見http://tools.ietf.org/html/rfc3778

編輯:完全忽略了「另存爲.pdf」的問題。 您還需要添加類似:

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

告訴瀏覽器默認的文件名應該是什麼。