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

4

2 回答 2

2

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

 PdfGenerator.getBuilder()
                        .setContext(context)
                        .fromLayoutXMLSource()
                        .fromLayoutXML(R.layout.layout_print,R.layout.layout_print)
                        .setDefaultPageSize(PdfGenerator.PageSize.A4)
                        .setFileName("Test-PDF")
                        .build();
于 2020-09-16T05:37:58.653 回答
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>

您可以根据需要创建任意数量的页面/模板。

  1. 实现视图渲染器

通过扩展 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);
于 2017-08-03T18:08:52.287 回答