问题描述
所以我正在尝试从 Web 视图创建 PDF.现在我可以从 webview 创建图像,但是我在将文档拆分成多个页面时遇到了一些问题.
So I am trying to create a PDF from a Webview. Right now I can create an image from the webview, but I am having some problems to split my document in many pages.
首先,我从 webview 创建一个位图:
First, I create a Bitmap from the webview:
public static Bitmap screenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return bitmap;
}
其次,我创建并显示 PDF:
Second, I create and I show the PDF:
public void criaPdf(){
Bitmap bitmap = Utils.screenShot(mContratoWebview);
Document doc = new Document();
File dir = new File(getFilesDir(), "app_imageDir");
if(!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, "contratoPdf.pdf");
try {
FileOutputStream fOut = new FileOutputStream(file);
PdfWriter.getInstance(doc, fOut);
//open the document
doc.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Image image = Image.getInstance(byteArray);
image.scaleToFit(PageSize.A4.getHeight(), PageSize.A4.getWidth());
doc.newPage();
doc.add(image);
} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
}
finally {
doc.close();
}
mPdfView.fromFile(file)
.pages(0, 1) // all pages are displayed by default
.enableSwipe(true)
.load();
mPdfView.setVisibility(View.VISIBLE);
}
这是我目前得到的:
所以我的问题是:Webview 的内容太大,无法放入 PDF.我该如何解决这个问题?
推荐答案
WebView 具有生成 PDF 的内置功能,通过使用专门用于打印的 PrintManager 服务使其可用.但是对于您的特定用例,我建议您将 WebView 的 PrintAdapter 的最终输出编写(存储)到本地文件,然后从那里开始.
WebView has built-in functionality to generate PDF's which is made available by using PrintManager Service specifically for the purpose of printing. But for your specific usecase I would suggest you to write(store) the final output of WebView's PrintAdapter which is a PDF file to a local file and go from there.
此链接将引导您了解详细信息和实施.http://www.annalytics.co.uk/android/pdf/2017/04/06/Save-PDF-From-An-Android-WebView/
This link will walk you through the details and implementation.http://www.annalytics.co.uk/android/pdf/2017/04/06/Save-PDF-From-An-Android-WebView/
您可以通过对上述解决方案进行小幅调整来实现 API 级别 19(KitKat) 兼容性.
You can achieve API level 19(KitKat) compatibility with small tweaks for the above solution.
这应该可以解决您的问题,但如果您在实施过程中遇到任何问题,请告诉我.
This should solve your problem but incase you face any issue with the implementation let me know.
这篇关于在 Android 上从 Webview 创建 PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!