【发布时间】:2015-01-05 20:14:46
【问题描述】:
我一直无法在 Android 上打印 PDF。我要做的是在 WebView 中呈现一些 HTML,然后在 PDF 画布上绘制 WebView 内容,最后将 PDF 写入文件。我遇到的问题是,当我绘制到 PDF 画布时,即使还有大量画布,内容也会被剪裁。我尝试使用.clipRect(Rect rect, Op op) 调整画布大小,虽然效果不错,但效果不如我所愿。
我也不知道如何可靠地将 HTML px 测量值转换为 PDF PostScript 1/72 英寸测量值。
这是我正在使用的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView wv = (WebView) this.findViewById(R.id.webView1);
wv.loadUrl("file:///android_asset/temp.html");
}
public void button1onClick(View v)
{
//Create PDF document
PdfDocument doc = new PdfDocument();
//Create A4 sized PDF page
PageInfo pageInfo = new PageInfo.Builder(595,842,1).create();
Page page = doc.startPage(pageInfo);
WebView wv = (WebView) this.findViewById(R.id.webView1);
page.getCanvas().setDensity(200);
//Draw the webview to the canvas
wv.draw(page.getCanvas());
doc.finishPage(page);
try
{
//Create the PDF file
File root = Environment.getExternalStorageDirectory();
File file = new File(root,"webview.pdf");
FileOutputStream out = new FileOutputStream(file);
doc.writeTo(out);
out.close();
doc.close();
//Open the PDF
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
}
catch(Exception e)
{
throw new RuntimeException("Error generating file", e);
}
}
基本上,该程序只是将 temp.html 文件加载到 webview 并为我呈现一个可用于创建 PDF 的按钮。
temp.html 文件如下所示:
<html>
<head>
<style>
div.border
{
width:600px;
height:800px;
border:1px solid black;
}
</style>
</head>
<body>
<div class="border"></div>
</body>
这是手动添加黑色边框以显示比例的结果:
我非常感谢一些关于如何在 Android 上可靠地将 HTML 转换为 PDF 的提示,而无需使用需要商业用途许可的库。
【问题讨论】:
标签: android pdf webview android-canvas