【问题标题】:android create pdf file from html textandroid从html文本创建pdf文件
【发布时间】:2015-01-29 07:44:37
【问题描述】:

这是我将 html 转换为 pdf 的代码:

public boolean create (String htmlText, String absoluteFilePath) {
try {
    Document document = new Document(PageSize.LETTER);
    PdfWriter pdfWriter = PdfWriter.getInstance
            (document, new FileOutputStream(absoluteFilePath));
    document.open();

    // Fixing xhtml tag
    Tidy tidy = new Tidy(); // obtain a new Tidy instance
    tidy.setXHTML(true); // set desired config options using tidy setters
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    tidy.setCharEncoding(Configuration.UTF8);
    tidy.parse(new ByteArrayInputStream(htmlText.getBytes(), output);
    String preparedText = output.toString("UTF-8");

    Log.i("CHECKING", "JTidy Out: " + preparedText);

    InputStream inputStream = new ByteArrayInputStream(preparedText.getBytes());
    XMLWorkerHelper.getInstance().parseXHtml(pdfWriter, document,
            inputStream, null, Charset.forName("UTF-8"), new MyFont());

    document.close();
    return true;
} catch (Exception e) {
    File file = new File(absoluteFilePath);
    if(file.exists()) {
        boolean isDeleted = file.delete();
        Log.i("CHECKING", "PDF isDeleted: " + isDeleted);
    }
    LOGGER.error("Exception: " + e.getMessage());
    e.printStackTrace();
    return false;
}

}

它适用于以下htmlText

   <p dir="ltr"><br>
wwwww<br>
--- <br>
Sent bys.</p>


<p>Original message:</p>
<blockquote>
<strong>From: </strong>
nakhmedov@s.com
<br/>
<strong>Sent: </strong>
Dec 1, 2014 5:10:19 PM
<br/>
<strong>
To: 
</strong>
ssss
<br/>
<strong>Subject: </strong>
test
<br/>
<br/>
<p dir="ltr">
<br>
123<br>
--- <br>
ssssssss.</p>
</blockquote>

它在 htmlText 之后不起作用:

<p dir="ltr"><br>
123<br>
--- <br>
Sent by ss.</p>


<p>Original message:</p>
<blockquote>
<strong>From: </strong>
Navruzbek Akhmedov <akhmedovnavruzbek@gmail.com>
<br/>
<strong>Sent: </strong>
Dec 1, 2014 5:14:36 PM
<br/>
<strong>
To: 
</strong>
Navruzbek Akhmedov <nakhmedov@sss.com>
<br/>
<strong>Subject: </strong>
test
<br/>
<br/>
<div dir="ltr">12345</div>
</blockquote>

请帮助我为什么它的工作方式不同并且它给出了第二个 htmlText document has no pages 的错误并且在此 tidy.parse(new ByteArrayInputStream(htmlText.getBytes("ISO-8859-1")), output); 之后输出流为空。提前致谢!

【问题讨论】:

  • 我错过了吗?也许 html 文本无效,这不起作用!
  • 它就像一个魅力:)))))))))
  • 你是在用iText转换pdf吗?
  • @Hunt Yes :) compile 'com.itextpdf:itextpdf:5.5.3' compile 'com.itextpdf.tool:xmlworker:5.5.3' compile 'jtidy:jtidy:4aug2000r7-dev'

标签: android html pdf itext


【解决方案1】:

我最近解决了这个问题。问题是 html 文本中的 Navruzbek Akhmedov &lt;akhmedovnavruzbek@gmail.com&gt;。在我看来,iText lib 将&lt;akhmedovnavruzbek@gmail.com&gt; 视为 HTML 标记。它实际上没有在 html 标签列表中然后给出错误。就这样! :))))))))))))))))))))))))))

【讨论】:

    猜你喜欢
    • 2017-05-22
    • 2011-05-25
    • 2017-06-19
    • 2017-10-20
    • 2013-11-11
    • 2011-06-23
    • 2017-11-03
    • 2013-03-26
    • 2011-10-08
    相关资源
    最近更新 更多