繁体   English   中英

如何在android中将xml布局转换为pdf

[英]How to convert xml layout to pdf in android

我在互联网上尝试了很多搜索,但没有找到任何解决方案。 我的问题是我有一个名为 main.xml 的布局,它的父布局是一个 LinearLayout 并且它是可滚动的。 我想生成该布局的pdf。 布局由报告组成,所以我想以 pdf 格式导出这些报告。 我该怎么做 请帮忙。

您可以使用这个来轻松完成几行代码 -

 PdfGenerator.getBuilder()
                        .setContext(context)
                        .fromLayoutXMLSource()
                        .fromLayoutXML(R.layout.layout_your_scroll_view)
                        .setDefaultPageSize(PdfGenerator.PageSize.A4)
                        .setFileName("Test-PDF")
                        .build();

您还可以在其中设置膨胀的滚动视图实例(单个或多个视图)。 此外,您还可以在PdfGeneratorListener()传递回调( PdfGeneratorListener() .build()以通知 pdf 生成是否已完成或因异常而失败

最后我得到了我的问题的解决方案。 现在我可以使用 itextpdf.jar 文件轻松地将任何视图转换为 PDF。 我将在这里发布我的代码。 此方法将以位图格式保存视图。

public void saveViewImage(View view){
    File file = saveBitMap(this, layout);    //which view you want to pass that view as parameter
    if (file != null) {
        Log.i("TAG", "Drawing saved to the gallery!");
    } else {
        Log.i("TAG", "Oops! Image could not be saved.");
    }
}

private File saveBitMap(Context context, View drawView){
    File pictureFileDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"Handcare");
    if (!pictureFileDir.exists()) {
        boolean isDirectoryCreated = pictureFileDir.mkdirs();
        if(!isDirectoryCreated)
            Log.i("ATG", "Can't create directory to save the image");
        return null;
    }
    String filename = pictureFileDir.getPath() +File.separator+ System.currentTimeMillis()+".jpg";
    File pictureFile = new File(filename);
    Bitmap bitmap =getBitmapFromView(drawView);
    try {
        createPdf(bitmap);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        pictureFile.createNewFile();
        FileOutputStream oStream = new FileOutputStream(pictureFile);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, oStream);
        oStream.flush();
        oStream.close();
    } catch (IOException e) {
        e.printStackTrace();
        Log.i("TAG", "There was an issue saving the image.");
    }
    scanGallery( context,pictureFile.getAbsolutePath());
    return pictureFile;
}
//create bitmap from view and returns it
private Bitmap getBitmapFromView(View view) {
    //Define a bitmap with the same size as the view
    Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
    //Bind a canvas to it
    Canvas canvas = new Canvas(returnedBitmap);
    //Get the view's background
    Drawable bgDrawable =view.getBackground();
    if (bgDrawable!=null) {
        //has background drawable, then draw it on the canvas
        bgDrawable.draw(canvas);
    }   else{
        //does not have background drawable, then draw white background on the canvas
        canvas.drawColor(Color.WHITE);
    }
    // draw the view on the canvas
    view.draw(canvas);
    //return the bitmap
    return returnedBitmap;
}

现在使用以下方法生成pdf

private void createPdf(Bitmap bitmap) throws IOException, DocumentException {

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    Image signature;
    signature = Image.getInstance(stream.toByteArray());
    signature.setAbsolutePosition(50f, 100f);
    signature.scalePercent(60f);
    //Image image = Image.getInstance(byteArray);
    File pdfFolder = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOCUMENTS), "pdfdemo");
    if (!pdfFolder.exists()) {
        pdfFolder.mkdirs();
        Log.i("Created", "Pdf Directory created");
    }

    //Create time stamp
    Date date = new Date() ;
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date);

    File myFile = new File(pdfFolder + timeStamp + ".pdf");

    OutputStream output = new FileOutputStream(myFile);
    //Step 1
    Document document = new Document();

    //Step 2
    PdfWriter.getInstance(document, output);

    //Step 3
    document.open();

    //Step 4 Add content
    document.add(signature);
    //document.add(new Paragraph(text.getText().toString()));
    //document.add(new Paragraph(mBodyEditText.getText().toString()));

    //Step 5: Close the document
    document.close();
}

暂无
暂无

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

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