使用PdfDocument在android中生成具有自定义大小的PDF [英] Generating a PDF with custom size in android with PdfDocument
问题描述
PdfDocument 是一个类,可以生成一个来自Android视图的PDF.您只需将视图添加到PdfDocument
,然后将PDF保存到内存中即可.
PdfDocument is a class that makes it possible to generate a PDF from an Android View. You simply add a View to PdfDocument
and then save the PDF to memory.
但是,我不想添加已经在屏幕上呈现的视图,因为这样的视图仅适用于智能手机屏幕,并且我想为打印机生成PDF文档.
However, I wouldn't like to add a View that is already rendered in the screen, because such View is only good for smartphone screens, and I want to generate a PDF document for printers.
因此,我想传递一个不渲染的视图.虽然我当然可以这样做,但是如何确定尺寸和比例呢?如何在我的PDF中控制它?
Therefore, I want to pass a View without rendering. While it's certainly possible for me to do that, how would the dimensions and proportions be decided? How can I control this in my PDF?
更新:
按照以下clotodex的回答,我做了:
Following the answer below from clotodex, I did:
LayoutInflater inflater = getLayoutInflater();
View linearview;
linearview = inflater.inflate(R.layout.printed_order,
findViewById(android.R.id.content),
false);
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(2480, 3508, 0).create();
PdfDocument.Page page = document.startPage(pageInfo);
linearview.draw(page.getCanvas());
document.finishPage(page);
OutputStream outStream;
File file = new File(getExternalFilesDir(null), "pedido.PDF");
try {
outStream = new FileOutputStream(file);
document.writeTo(outStream);
document.close();
outStream.flush();
outStream.close();
但是我得到一个空的PDF.如果我这样做
but I get an empty PDF. If I do
View view = findViewById(android.R.id.content);
view.draw(page.getCanvas());
代替
linearview.draw(page.getCanvas());
我得到了我正在进行的活动,这证实了所有事情都是严谨的,除了我要打印的视图之外.
I get the activity I'm in, which confirms everything is rigth, except for the view that I'm trying to print.
推荐答案
看看这个问题在Android中,视图的尺寸由父级布局给出.
这意味着您可以使用所需的尺寸创建新的布局,并使用attachToRoot=false
和root=your_new_layout
扩展视图.
In Android the measurements for a view are given by the parent layout.
This means you can create a new layout with your desired measurements and inflate your view with attachToRoot=false
and root=your_new_layout
.
渲染视图后,现在就可以像将渲染的视图绘制为pdf一样进行操作(按照链接中的说明进行操作,或者在绘制到页面画布之前将其转换为位图).
When you have rendered the view you can now proceed as you would with drawing a rendered view to pdf (following the instruction in your link or converting it to a bitmap before drawing to the page canvas).
这篇关于使用PdfDocument在android中生成具有自定义大小的PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!