将XML(Android源代码)转换为PDF

3
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。我使用下面的代码,但是当我点击生成器按钮时,应用程序突然关闭,并且SD卡中没有pdf文件(我的xml和xsl文件在布局目录中)。


你尝试过检查logcat吗?也许你可以重新创建崩溃并在此处发布结果的logcat。 - TJ Thind
如果我把“OutputStream out = new java.io.FileOutputStream(pdffile);”放在try catch里面,应用程序就会停止,但是如果我把它放出来,一个大小为0 kb的PDF文件就会出现,应用程序再次停止......所以我猜测try catch没有正常工作或者类似于那样的问题... :s - Hichem Bili
我想知道,当应用程序安装时,项目文件路径是否与它们在工作区中的路径相同?(我知道“项目名称=根目录”) - Hichem Bili
2个回答

2
您可以使用这个库来轻松地在几行代码内完成 - 链接
 PdfGenerator.getBuilder()
                        .setContext(context)
                        .fromLayoutXMLSource()
                        .fromLayoutXML(R.layout.layout_print,R.layout.layout_print)
                        .setFileName("Test-PDF")
                        .build();

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

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

说明

  1. 创建XML布局

首先创建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>

你可以创建尽可能多的页面/模板。
2. 实现视图渲染器
通过扩展AbstractViewRenderer或匿名实例化并注入布局id来实现你的视图渲染器。initView(View view)将自动提供一个已膨胀的视图。还有其他选项,但我现在不会涵盖它们。
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文档

使用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);

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