gpt4 book ai didi

android - 在 Android 上从 Webview 创建 PDF

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:04:09 25 4
gpt4 key购买 nike

所以我正在尝试从 Webview 创建 PDF。现在我可以从 webview 创建图像,但是我在将我的文档拆分为多个页面时遇到了一些问题。

首先,我从 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:

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);
}

这是我到目前为止得到的:

enter image description here

所以我的问题是:Webview 的内容太大,PDF 放不下。我该如何解决这个问题?

最佳答案

WebView 具有生成 PDF 的内置功能,可通过使用 PrintManager 服务专门用于打印。但是对于您的特定用例,我建议您将 WebView 的 PrintAdapter 的最终输出(一个 PDF 文件)写入(存储)到本地文件,然后从那里开始。

此链接将引导您完成详细信息和实现。 http://www.annalytics.co.uk/android/pdf/2017/04/06/Save-PDF-From-An-Android-WebView/

您可以通过对上述解决方案进行小的调整来实现 API 级别 19 (KitKat) 兼容性。

这应该可以解决您的问题,但如果您在实现过程中遇到任何问题,请告诉我。

关于android - 在 Android 上从 Webview 创建 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42376613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com