1

我想将 html 文件转换为 pdf 我的代码是

Document document = new Document();
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
    mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    mExternalStorageAvailable = true;
    mExternalStorageWriteable = false;
} else {
    mExternalStorageAvailable = mExternalStorageWriteable = false;
}
String file = null;
if (mExternalStorageWriteable) {
    file = Environment.getExternalStorageDirectory() + "/abcd.pdf";
}

document.open();
PdfCopy writer = new PdfCopy(document, new FileOutputStream(file));

InputStream is = new FileInputStream(Environment.getExternalStorageDirectory()+"/new1.html");

PdfReader reader = new PdfReader(is);

PdfImportedPage page;
int n = reader.getNumberOfPages();
page = writer.getImportedPage(reader, n);
Image instance = Image.getInstance(page);
document.add(instance);

document.close();
Toast.makeText(this, "pdf created", Toast.LENGTH_LONG).show();

我用过itextpdf-5.4.3.jar。在运行此代码时,我收到一个异常“找不到 PDF 标头签名”......任何人都可以帮助我

4

2 回答 2

5

此类独立于 iText 工作但要编译,它必须在包“.../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.
于 2017-11-18T12:35:16.767 回答
0

该错误是因为您尝试使用PdfReader.

您可以查看“iText in Action”一书中的HtmlMovies1HTMLWorker示例,该示例使用已弃用的 HTML 到 PDF 转换,或者查看新XML Worker项目的 API 文档。

于 2013-08-19T14:01:39.480 回答