HTML到PDF利用iText xmlworker(html to pdf using itext

2019-10-18 15:31发布

   Document document = new Document(PageSize.A4, ml, mr, mt, mb);
   PdfWriter writer=PdfWriter.getInstance(document, response.getOutputStream());
   String sc_na=request.getParameter("school_name");
   String name=sc_na;
   writer.setPageEvent(new HeaderAndFooter(name));
   document.open();
   XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
   //HTMLWorker htmlWorker = new HTMLWorker(document);
   Class.forName("com.mysql.jdbc.Driver");
   Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/elect", "root", "root");
   Statement st=con.createStatement();
   ResultSet rs=st.executeQuery("Select * from test3");
   List arrlist = new ArrayList();
   while(rs.next()){
   String xa =rs.getString("display");
   if(xa.equals("1")){
    arrlist.add(rs.getString("question_text"));
   }
 }
 Collections.shuffle(arrlist); 
for(int i=0;i<nb;i++){
    String str = (String) arrlist.get(i);
     worker.parseXHtml(writer, document, new StringReader("<br>"));
     worker.parseXHtml(writer, document, new StringReader(str));

}
document.close();

这是我code.Using的片段,我得到我在一个单一的column.What所有的数据,我应该这样做,我可以进入多个columns.One方式我想是使用PDFptable但我怎么应用它here.Please帮助。

Answer 1:

对于HTML为PDF格式,请使用飞碟: http://code.google.com/p/flying-saucer/

它使用的iText 2.0.8,它尊重一个CSS。 这是尽可能多的代码:

 org.w3c.dom.Document doc = . . .
 ITextRenderer renderer = new ITextRenderer();
 renderer.setDocument(doc, null);

 renderer.layout();
 renderer.createPDF(out);

确保你的XHTML链接到一个到达CSS,如

 <link rel="stylesheet" type="text/css" href="file://. . ./pdf.css" media="print"/>


文章来源: html to pdf using itext xmlworker