使用Android创建包含多个页面的PDF文档,其中内容来自WebView。

11
我正在使用Android的PdfDocument框架(链接)来创建一个包含我的webview内容的pdf文档。虽然pdf文档创建得很好,但只有一页。当webview内容较大时,我需要创建一个多页文档。我只需要将webview内容拆分成多个页面。我该如何做到这一点?我不想使用iText或任何第三方库。请帮帮我。先感谢您的帮助。
// create a new document
PdfDocument document = new PdfDocument();

// create a page description
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(width, height, 1).create();

// start a page
PdfDocument.Page page = document.startPage(pageInfo);

// draw something on the page
View content = myWebview;
content.draw(page.getCanvas());

// finish the page
document.finishPage(page);

FileOutputStream fos;
try {
    fos = new FileOutputStream(fileNameWithPath, false);
    // write the document content
    document.writeTo(fos);

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

// close the document
document.close();

你找到解决办法了吗?我也在尝试解决它。 - Annabelle
@Annabelle,你找到任何解决方案了吗? - Rucha Bhatt Joshi
很遗憾,我没有。这个问题对我仍然有效。 - Annabelle
2个回答

7
如果您想创建多个页面,则只需为要在文档中创建的每个页面调用startPage()和finishPage()。
像这样:
// create document
PdfDocument document = new PdfDocument();

// create a page description
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(width, height, 1).create();

// start 1st page
PdfDocument.Page page = document.startPage(pageInfo);
// draw something on the page
View content = myWebview;
content.draw(page.getCanvas());
// finish 1st page
document.finishPage(page);

// start 2nd page
PdfDocument.Page page = document.startPage(pageInfo);
// draw something on the page
View content = someOtherWebview;
content.draw(page.getCanvas());
// finish 2nd page
document.finishPage(page);

// and so on...

FileOutputStream fos;
try {
    fos = new FileOutputStream(fileNameWithPath, false);
    // write the document content
    document.writeTo(fos);

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

// close the document
document.close();

我知道我可以添加更多页面,但我想要的是将Web视图内容分成多个页面,如果该内容对于ISO A4页面来说太长了。 - user3065901
好的,我明白你遇到了长内容的问题。我不知道你如何截断并将内容分段放在多个页面上。也许你可以获取你的 Webview 的高度并缩放你的画布? - rtome

2

最近几天我一直遇到这个问题,所以我找到了Rakesh Gopathi的答案,这个方法完美地解决了我的问题。我强烈推荐所有使用本机PdfDocument类的人去试一试。


我检查了它,它运行良好,但我仍然无法创建多个页面,只能创建单个页面。 - Rucha Bhatt Joshi
对我来说,它按预期工作了。多个页面被创建。 - Vlad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接