java html如何转成pdf?-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文

java html如何转成pdf?

蛮大人123 2016-03-04 17:54:03 3486

求助一个能支持中文,支持css,支持table标签及boder和colspan属性的解决方案
尝试使用过

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
    new FileOutputStream("pdf.pdf"));
document.open();
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
    new FileInputStream("index.html"));
document.close();
System.out.println("PDF Created!");

使用jar包版本 itextpdf 5.4.2.jar和xmlworker.5.4.jar 不支持中文

云服务器登录 云服务器设置
分享到
取消 提交回答
全部回答(1)
  • 蛮大人123
    2019-07-17 18:52:40

    HTML File:

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
        <head>
            <title>HTML to PDF</title>
            <link href="style.css" rel="stylesheet" type="text/css" />
        </head>
        <body>
            <h1>HTML to PDF</h1>
            <p>
                <span class="itext">itext</span> 5.4.2 <span class="description"> converting HTML to PDF</span>
            </p>
            <table>
              <tr>
                    <th class="label">Title</th>
                    <td>iText - Java HTML to PDF</td>
                </tr>
                <tr>
                    <th>URL</th>
                    <td>http://hmkcode.com/itext-html-to-pdf-using-java</td>
                </tr>
            </table>
        </body>
    </html>

    style.css:

    h1 {
      color:#ccc;
    }
    table tr td{
        text-align:center;
        border:1px solid gray;
        padding:4px;
    }
    table tr th{
        background-color:#84C7FD;
        color:#fff;
        width: 100px;
    }
    .itext{
        color:#84C7FD;
        font-weight:bold;
    }
    .description{
        color:gray;
    }

    1
    Java:

    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import com.itextpdf.text.Document;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.pdf.PdfWriter;
    import com.itextpdf.tool.xml.XMLWorkerHelper;
     
    public class App 
    {
        public static void main( String[] args ) throws DocumentException, IOException
        {
          // step 1
            Document document = new Document();
            // step 2
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("pdf.pdf"));
            // step 3
            document.open();
            // step 4
            XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                    new FileInputStream("index.html")); 
            //step 5
             document.close();
     
            System.out.println( "PDF Created!" );
        }
    }

    Output “PDF”
    2

    0 0
开发与运维
使用钉钉扫一扫加入圈子
+ 订阅

集结各类场景实战经验,助你开发运维畅行无忧

相似问题
最新问题