将安卓布局转换为PDF文件

13

如何将Android布局转换为PDF文件?这是否可能?
如果可能,如何进行Android布局到PDF的转换?
欢迎提供建议。谢谢。


1
你可以将布局转换为位图并放置在PDF中,没什么大不了的。 - jagapathi
4个回答

6
我尝试了很多方法。
最后找到了一个答案,使用了这个库:https://mvnrepository.com/artifact/com.itextpdf/itextpdf/5.0.6
将布局转换为图像并将其放置在pdf中
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;

String dirpath;
public void layoutToImage(View view) {
    // get view group using reference  
    relativeLayout = (RelativeLayout) view.findViewById(R.id.print);
    // convert view group to bitmap
    relativeLayout.setDrawingCacheEnabled(true);
    relativeLayout.buildDrawingCache();
    Bitmap bm = relativeLayout.getDrawingCache();
    Intent share = new Intent(Intent.ACTION_SEND);
    share.setType("image/jpeg");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

    File f = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
    try {
        f.createNewFile();
        FileOutputStream fo = new FileOutputStream(f);
        fo.write(bytes.toByteArray());
    } catch (IOException e) {
        e.printStackTrace();
    }

}
public void imageToPDF() throws FileNotFoundException {
    try {
        Document document = new Document();
        dirpath = android.os.Environment.getExternalStorageDirectory().toString();
        PdfWriter.getInstance(document, new FileOutputStream(dirpath + "/NewPDF.pdf")); //  Change pdf's name.
        document.open();
        Image img = Image.getInstance(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");  
        float scaler = ((document.getPageSize().getWidth() - document.leftMargin()
                - document.rightMargin() - 0) / img.getWidth()) * 100; 
        img.scalePercent(scaler);
        img.setAlignment(Image.ALIGN_CENTER | Image.ALIGN_TOP);
        document.add(img);
        document.close();
        Toast.makeText(this, "PDF Generated successfully!..", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {

    }
}

1
你说“无法将视图组转换为图像”,但实际上你已经在你的代码中完成了这个操作。 - nyconing
无法直接将布局转换为图像。需要先将布局转换为位图,然后再转换为图像。@nyconing - Thirumal Govindaraj
@ThirumalGovindaraj 在哪里需要调用 imageToPDF? - kartheeki j
最初需要创建图像,然后将该图像添加到文档对象中(***document.add(img);***)。 - Thirumal Govindaraj
图像在转换为PDF后被裁剪。 - Shikhar

4

3
以上答案是正确的,它在以下一行抛出异常错误。
 bm.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

由于这行代码返回null。
  Bitmap bm = relativeLayout.getDrawingCache();

所以我对位图为空的问题进行了更多的研究。我使用了这种方法,首先将视图转换为图像。然后你可以使用上面的函数imageToPDF(),它运行良好。下面是我的方法。

 public void convertCertViewToImage()
 {

        scrollView.setDrawingCacheEnabled(true);
        scrollView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        scrollView.layout(0, 0, scrollView.getMeasuredWidth(), scrollView.getMeasuredHeight());
        scrollView.buildDrawingCache();
        Bitmap bm = Bitmap.createBitmap(scrollView.getDrawingCache());
        scrollView.setDrawingCacheEnabled(false); // clear drawing cache
        Intent share = new Intent(Intent.ACTION_SEND);
        share.setType("image/jpg");

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

        File f = new File(getExternalFilesDir(null).getAbsolutePath() + File.separator + "Certificate" + File.separator + "myCertificate.jpg");

        f.createNewFile();
        FileOutputStream fo = new FileOutputStream(f);
        fo.write(bytes.toByteArray());

} 

2

我制作了一个来实现这个目标。

主要的代码片段是 -

 PdfGenerator.getBuilder()
                        .setContext(context)
                        .fromLayoutXMLSource()
                        .fromLayoutXML(R.layout.layout_print,R.layout.layout_print)
            /* "fromLayoutXML()" takes array of layout resources.
             * You can also invoke "fromLayoutXMLList()" method here which takes list of layout resources instead of array. */
                        .setDefaultPageSize(PdfGenerator.PageSize.A4)
            /* It takes default page size like A4,A5. You can also set custom page size in pixel
             * by calling ".setCustomPageSize(int widthInPX, int heightInPX)" here. */
                        .setFileName("Test-PDF")
            /* It is file name */
                        .setFolderName("FolderA/FolderB/FolderC")
            /* It is folder name. If you set the folder name like this pattern (FolderA/FolderB/FolderC), then
             * FolderA creates first.Then FolderB inside FolderB and also FolderC inside the FolderB and finally
             * the pdf file named "Test-PDF.pdf" will be store inside the FolderB. */
                        .openPDFafterGeneration(true)
            /* It true then the generated pdf will be shown after generated. */
                        .build(new PdfGeneratorListener() {
                            @Override
                            public void onFailure(FailureResponse failureResponse) {
                                super.onFailure(failureResponse);
                /* If pdf is not generated by an error then you will findout the reason behind it
                 * from this FailureResponse. */
                            }

                            @Override
                            public void showLog(String log) {
                                super.showLog(log);
                /*It shows logs of events inside the pdf generation process*/ 
                            }

                            @Override
                            public void onSuccess(SuccessResponse response) {
                                super.onSuccess(response);
                /* If PDF is generated successfully then you will find SuccessResponse 
                 * which holds the PdfDocument,File and path (where generated pdf is stored)*/
                
                            }
                        });

我尝试了这个库。但是它没有显示任何结果:(日志显示它已经成功创建。但是它只被带到文件管理器,没有任何pdf :( - Isuru Bandara
你的安卓API版本是多少? - Gk Mohammad Emon
最低SDK版本为19 - Isuru Bandara
1
它总是发送到下载文件夹,而不是我们定义的文件夹。 - Isuru Bandara
@IsuruBandara 我在新版本中修复了许多与文件夹和文件相关的问题。你可以试试看。 - Gk Mohammad Emon
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接