开发者社区> 问答> 正文

java html如何转成pdf?

求助一个能支持中文,支持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 不支持中文

展开
收起
蛮大人123 2016-03-04 17:54:03 4773 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    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

    2019-07-17 18:52:40
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
天猫 HTML5 互动技术实践 立即下载
EXTENDING SPARK WITH JAVA AGENTS 立即下载
天猫HTML5互动技术实践 立即下载