将xml(android源码)转换为pdf

时间:2013-04-06 18:07:39

标签: android xml pdf apache-fop

public void onClick(View v)     
{switch(v.getId())

    { case R.id.button1:

        try {


            // Setup directories
            File baseDir = new File("res/layout");
            File outDir = new File(baseDir, "/sdcard");
            outDir.mkdirs();

            // Setup input and output files
            File xmlfile = new File(baseDir, "activity_main.xml");
            File xsltfile = new File(baseDir, "test.xsl");
            File pdffile = new File(outDir, "ResultXML2PDF.pdf");   
                                    // configure fopFactory as desired
            FopFactory fopFactory = FopFactory.newInstance();

            FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
            // configure foUserAgent as desired

            // Setup output
            OutputStream out = new java.io.FileOutputStream(pdffile);
            out = new java.io.BufferedOutputStream(out);

            try {
                // Construct fop with desired output format
                Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

                // Setup XSLT
                TransformerFactory factory = TransformerFactory.newInstance();
                Transformer transformer = factory.newTransformer(new StreamSource(xsltfile));

                // Set the value of a <param> in the stylesheet
                transformer.setParameter("versionParam", "2.0");

                // Setup input for XSLT transformation
                Source src = new StreamSource(xmlfile);

                // Resulting SAX events (the generated FO) must be piped through to FOP
                Result res = new SAXResult(fop.getDefaultHandler());

                // Start XSLT transformation and FOP processing
                transformer.transform(src, res);
            } finally {
                out.close();
        }

            System.out.println("Success!");
        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(-1);
        }
        }
}    

标题

我想将包含我的视图的xml文件转换为pdf ..我的android应用程序必须生成此pdf。我使用下面的代码但是当我点击生成器按钮时,应用程序被sudunely关闭,并且sdcard中没有文件pdf(我的xml和xsl文件在布局库中)。

2 个答案:

答案 0 :(得分:1)

也许你可以看看这个链接:

https://github.com/HendrixString/Android-PdfMyXml

说明

  1. 创建XML布局
  2. 首先创建XML布局。根据比例1:1.41给出尺寸,以像素为单位(以及所有子视图)和比例,根据风景或肖像。

    page1.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="2115px"
                android:layout_height="1500px"
                android:background="@color/white">
     <TextView android:id="@+id/tv_hello"
                android:textColor="@color/black"
                android:textSize="27px"
                android:textStyle="bold"
                android:padding="6px"/>
    
    </RelativeLayout>
    

    您可以根据需要创建多个页面/模板。

    1. 实施视图渲染器
    2. 通过扩展AbstractViewRenderer或匿名实例化并注入布局ID来实现View渲染器。 initView(视图视图)将自动为您提供充气视图。还有其他选择,但我现在不介绍它。

      AbstractViewRenderer page = new AbstractViewRenderer(context, R.layout.page1) {
      private String _text;
      
      public void setText(String text) {
          _text = text;
      }
      
      @Override
      protected void initView(View view) {
          TextView tv_hello = (TextView)view.findViewById(R.id.tv_hello);
           tv_hello.setText(_text);
      }
      };
      
      // you can reuse the bitmap if you want
      page.setReuseBitmap(true);
      
      1. 构建PDF文档
      2. 使用PdfDocument或PdfDocument.Builder添加页面并使用进度条在后台渲染和运行它。

            PdfDocument doc            = new PdfDocument(ctx);
        
        // add as many pages as you have
        doc.addPage(page);
        
        doc.setRenderWidth(2115);
        doc.setRenderHeight(1500);
        doc.setOrientation(PdfDocument.A4_MODE.LANDSCAPE);
        doc.setProgressTitle(R.string.gen_please_wait);
        doc.setProgressMessage(R.string.gen_pdf_file);
        doc.setFileName("test");
        doc.setInflateOnMainThread(false);
        doc.setListener(new PdfDocument.Callback() {
            @Override
            public void onComplete(File file) {
                Log.i(PdfDocument.TAG_PDF_MY_XML, "Complete");
            }
        
            @Override
            public void onError(Exception e) {
                Log.i(PdfDocument.TAG_PDF_MY_XML, "Error");
            }
        });
        
        doc.createPdf(ctx);
        

        或使用PdfDocument.Builder

        new PdfDocument.Builder(ctx).addPage(page).filename("test").orientation(PdfDocument.A4_MODE.LANDSCAPE)
                                 .progressMessage(R.string.gen_pdf_file).progressTitle(R.string.gen_please_wait).renderWidth(2115).renderHeight(1500)
                                 .listener(new PdfDocument.Callback() {
                                     @Override
                                     public void onComplete(File file) {
                                         Log.i(PdfDocument.TAG_PDF_MY_XML, "Complete");
                                     }
        
                                     @Override
                                     public void onError(Exception e) {
                                         Log.i(PdfDocument.TAG_PDF_MY_XML, "Error");
                                     }
                                 }).create().createPdf(this);
        

答案 1 :(得分:0)

您可以使用此library简化几行代码中的操作-

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