I've been having troubles getting PDF printing work on Android. What I'm trying to do is render some HTML in WebView, then draw the WebView contents on a PDF canvas and finally write the PDF to a file. The problem I'm having is that when I draw to the PDF canvas the content gets clipped even though there is plenty of canvas left. I've tried resizing the canvas using the .clipRect(Rect rect, Op op)
and that kind of worked but not as well as I would've liked.
I also have no idea how I can translate the HTML px measurements to the PDF PostScript 1/72th inch measurements reliably.
Here's the code I'm using:
@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);
}
}
Basically the program just loads the temp.html file to webview and renders me a button that I can use to create the PDF.
The temp.html file looks like:
<html>
<head>
<style>
div.border
{
width:600px;
height:800px;
border:1px solid black;
}
</style>
</head>
<body>
<div class="border"></div>
</body>
And here is the result with manually added black border to show the scale:
I would really appreciate some tips on how to convert HTML to PDF reliably on Android without using libraries that require licenses for commercial use.