使用 PdfDocument 将 Html 转换为 PDF

Day*_*iel 1 android

我正在尝试使用 PdfDocument 从 HTML 字符串生成 PDF:

https://developer.android.com/reference/android/graphics/pdf/PdfDocument.html

字符串示例:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
            <title>Example</title>
        </head>
        <body>
            <h1>Hello</h1>
        </body>
    </html>
Run Code Online (Sandbox Code Playgroud)

我知道如何从 WebView 生成 PDF 文件,但不知道如何从字符串 HTML 生成 PDF 文件。我怎么做?我在 stackoverflow.com 或 Google 中没有找到如何使用本机类 PDFDOCUMENT 执行此操作

Isl*_*lah 5

这个做你正在寻找的。

但是要编译,它必须在包“.../java/android/print/”中

这是一个简单的代码示例:

PdfConverter converter = PdfConverter.getInstance();
File file = new File(Environment.getExternalStorageDirectory().toString(), "file.pdf");
String htmlString = "<html><body><p>WHITE (default)</p></body></html>";
converter.convert(getContext(), htmlString, file);
// By now the pdf has been printed in the file.
Run Code Online (Sandbox Code Playgroud)