gpt4 book ai didi

android - 如何在 android 中从 webview 创建 PDF?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:39:38 26 4
gpt4 key购买 nike

我在 webview 中显示 webpage。现在如何从 WebView 创建PDF

例如:webview 加载 URL 是 "www.google.co.in"。现在如何将此网页另存为图像并创建 pdf ??

任何帮助将不胜感激

最佳答案

这样试试

WebView 有一个名为 setPictureListener 的内置方法,如下所示使用该方法

webView1.setPictureListener(new PictureListener() {

public void onNewPicture(WebView view, Picture picture) {
if (picture != null) {
try {
bmp = pictureDrawable2Bitmap(new PictureDrawable(
picture));

} catch (Exception e) {
e.printStackTrace();
}
}
}
});

为了获取位图,我使用了 pictureDrawable2Bitmap,这是一个

private static Bitmap pictureDrawable2Bitmap(PictureDrawable pictureDrawable) {
Bitmap bitmap = Bitmap.createBitmap(
pictureDrawable.getIntrinsicWidth(),
pictureDrawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawPicture(pictureDrawable.getPicture());
return bitmap;
}

现在你的位图已经准备好了,现在如下设置webview客户端

webView1.setWebViewClient(new myWebClient());

这里是 myWebClient

public class myWebClient extends WebViewClient {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub

view.loadUrl(url);
return true;

}

@Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
Log.i("OnPageLoadFinished", url);
img.setImageBitmap(bmp);
}

如页面加载完成所示,我设置了图像位图,它是您 webview 上当前加载的 url 的快照

现在位图已准备好使用 IText 库将该位图传递给 Pdf

这是一个在 iText 上使用下面的函数编写带有图像的 pdf 的示例

public void SimplePDFTable() throws Exception {

File direct = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/AamirPDF");
if (!direct.exists()) {
if (direct.mkdir()) {
Toast.makeText(MainActivity.this,
"Folder Is created in sd card", Toast.LENGTH_SHORT)
.show();
}
}
String test = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/AamirPDF";
Document document = new Document();

PdfWriter.getInstance(document, new FileOutputStream(test
+ "/mypdf.pdf"));

document.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Image image = Image.getInstance(byteArray);


image.scaleToFit(PageSize.A4.getHeight(), PageSize.A4.getWidth());
document.add(image);

document.close();

}

祝你好运

关于android - 如何在 android 中从 webview 创建 PDF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20511639/

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