简体   繁体   中英

How to create high quality PDF from a view in android studio (java)?

I want to create a PDF file of a linear layout of one of my activities. An example can be found in the following: https://medium.com/@strawberryinc0531/convert-xml-to-pdf-in-android-studio-using-pdfdocument-class-757dee166d50

I am creating a bitmap initially. With or without scaling, the generated pdf from the bitmap results in low-resolution content (ie, zoomed pdf file is blurry). Can I create a vectorized image of a linear layout to create a PDF?

Don't scale your Bitmap down to fit the PDF page size, set a scale on the Canvas you get from the PDF Document.

This stores the bitmap at the original resolution but displays it at the correct size to fit your page size. Thus as you zoom in on the PDF it does not pixelate until you run out of detail in the original bitmap.

eg

// Prep linearLayout to draw to Bitmap
....

// create page
PdfDocument.Page page = document.startPage(pageInfo);

Canvas pageCanvas = page.getCanvas();
// Work out scale to use to fit width of page
// In this instance the bitmap is wider than the height
// so we don't need to work out if we need a smaller scale to fit the height on to the page
float scaleWidth = (float) pageCanvas.getWidth() / linearLayout.getWidth();

// Draw the Layout to a bitmap at it's original size
Canvas bitmapCanvas = new Canvas();
Bitmap bitmap = Bitmap.createBitmap(linearLayout.getWidth(), linearLayout.getHeight(), Bitmap.Config.ARGB_8888);

bitmapCanvas.setBitmap(bitmap);
linearLayout.draw(bitmapCanvas);

// The important bit to set the page scale
pageCanvas.scale(scaleWidth, scaleWidth);

// Draw the original sized bitmap to page
Paint paint = new Paint();
paint.setAntiAlias(true);
pageCanvas.drawBitmap(bitmap,0,0,paint);

If you look at the PDF it creates

在此处输入图像描述

Thus in this instance the image contained in the PDF is 1322 x 669 but it is displayed in a MediaBox of 594 x 841, thus it has about 2.2 times more details to zoom in to

Another way is to draw your layout directly to the PDF page without going through a bitmap as this create create pdf "primatives" like text and line objects that scale better, BUT you have to size your layout to fit the PDF page size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM