在根据Android graphics pdf PdfDocument写Android上的PDF demo程序时,其中这一点是编译不过:
网上搜索了一下,参数的另一种写法是:
// crate a page description
PageInfo pageInfo = new PageInfo.Builder(595, 842, 1).create();
即这个API:
/**
* Creates a new builder with the mandatory page info attributes.
*
* @param pageWidth The page width in PostScript (1/72th of an inch).
* @param pageHeight The page height in PostScript (1/72th of an inch).
* @param pageNumber The page number.
*/
public Builder(int pageWidth, int pageHeight, int pageNumber) {
...
}
这里的长度单位写的是「1/72th of an inch」,一时不懂是什么意思,像A4这种标准尺寸一般会有ISO的毫米尺寸210297mm以及英寸长度8.27 in x 11.69 in,那「1/72th of an inch」又是什么呢?试着按照毫米和英寸填写,生成的PDF尺寸都不是A4大小。为了快速了解我以「PageInfo.Builder a4」为关键字在Google上找到了Android - Drawing to a PDF canvas from WebView,这里使用的参数是(595,842,1),我照着填上后生成的PDF确实是A4大小了,如下图:
然后经过简单的计算8.2772=595.44得出了他们之间的关系,这里要填写的数是inch*72。这里iso-paper-sizes也有说明:
其实这样直接填数字并不是一个好的方法,这里可以借用PrintAttributes.MediaSize类,这里已经有了很多标准尺寸值。取出其英寸值再进行运算就得出了这里要填写的数了。
// crate a page description
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(
PrintAttributes.MediaSize.ISO_A4.getWidthMils() * 72 / 1000,
PrintAttributes.MediaSize.ISO_A4.getHeightMils() * 72 / 1000, 1)
.create();
最后顺便贴一下在Activity中使用的完成Demo程序:
public void onClick(View v) {
// create a new document
PdfDocument document = new PdfDocument();
// crate a page description
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(
PrintAttributes.MediaSize.ISO_A4.getWidthMils() * 72 / 1000,
PrintAttributes.MediaSize.ISO_A4.getHeightMils() * 72 / 1000, 1)
.create();
// start a page
PdfDocument.Page page = document.startPage(pageInfo);
// draw something on the page
View content = findViewById(android.R.id.content);;
content.draw(page.getCanvas());
// finish the page
document.finishPage(page);
// add more pages
// write the document content
FileOutputStream os = null;
try {
String string = getExternalFilesDir(Environment.DIRECTORY_DCIM)
+ File.separator + "test.pdf";
Log.i(LOG_TAG, "String:" + string);
os = new FileOutputStream(string);
document.writeTo(os);
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// close the document
document.close();
}
}