简体   繁体   English

将android布局转换为PDF文件

[英]Convert android layout to PDF file

How to convert android layout to PDF file.如何将android布局转换为PDF文件。 Is it possible?.有可能吗?
If that is possible how to proceed to convert the android layout to PDF.如果可能的话,如何继续将 android 布局转换为 PDF。
suggestions are welcome.欢迎提出建议。 Thanks in advance.提前致谢。

I have tried many ways.我尝试了很多方法。
Finally got an answer Using this library https://mvnrepository.com/artifact/com.itextpdf/itextpdf/5.0.6终于得到了答案使用这个库https://mvnrepository.com/artifact/com.itextpdf/itextpdf/5.0.6
Layout to image and place it in pdf布局到图像并将其放置在 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) {

    }
}

您可以使用自定义库,例如https://github.com/HendrixString/Android-PdfMyXml但这里解释了另一种方法 - 如何将 Android 视图转换为 PDF - 生成包含布局位图的 pdf

The above answer is correct, it throws an Exception error at the following line.上面的答案是正确的,它在下一行抛出异常错误。

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

Bcoz of this line of code return null这行代码的 Bcoz 返回 null

  Bitmap bm = relativeLayout.getDrawingCache();

So I have done some more research on Bitmap coming null.I use this method which first converts view to Image.所以我对位图变为空做了更多的研究。我使用这种首先将视图转换为图像的方法。 Then you can use above function ie imageToPDF() which works well.Below is my method.然后你可以使用上面的函数,即 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());

} 

I made a library to achieve this objective.我做了一个图书馆来实现这个目标。

The main code snippet is -主要代码片段是-

 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)*/
                
                            }
                        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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