1/72th of an inch

在根据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.27
72=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();
    }
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

袁保康

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值