在android中将html转换为pdf

时间:2013-08-19 13:39:07

标签: android itext

我想将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标头签名” ......任何人都可以帮助我

2 个答案:

答案 0 :(得分:1)

class独立于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.

答案 1 :(得分:0)

错误是因为您尝试使用PdfReader将HTML文件读取为PDF文档。

您可以查看“iText in Action”一书中的HtmlMovies1示例,其中使用了弃用的HTMLWorker进行HTML到PDF转换,或者查看新版本的API文档{ {3}}项目。