如何在 Android 应用程序中创建 PDF?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2499960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:05:08  来源:igfitidea点击:

How to create PDFs in an Android app?

androidpdf

提问by nikib3ro

Is there any way to create PDF Files from an Android application?

有没有办法从 Android 应用程序创建 PDF 文件?

回答by nikib3ro

If anyone wants to generate PDFs on Android device, here is how to do it:

如果有人想在 Android 设备上生成 PDF,请按以下步骤操作:

回答by teh.fonsi

If you are developing for devices with API level 19 or higher you can use the built in PrintedPdfDocument: http://developer.android.com/reference/android/print/pdf/PrintedPdfDocument.html

如果您正在为 API 级别 19 或更高级别的设备进行开发,则可以使用内置的 PrintedPdfDocument:http: //developer.android.com/reference/android/print/pdf/PrintedPdfDocument.html

// open a new document
PrintedPdfDocument document = new PrintedPdfDocument(context,
     printAttributes);

// start a page
Page page = document.startPage(0);

// draw something on the page
View content = getContentView();
content.draw(page.getCanvas());

// finish the page
document.finishPage(page);
. . .
// add more pages
. . .
// write the document content
document.writeTo(getOutputStream());

//close the document
document.close();

回答by hrishitiwari

A trick to make a PDF with complex features is to make a dummy activity with the desired xml layout. You can then open this dummy activity, take a screenshot programmaticallyand convert that image to pdf using this library. Of course there are limitations such as not being able to scroll, not more than one page,but for a limited application this is quick and easy. Hope this helps someone!

制作具有复杂功能的 PDF 的一个技巧是使用所需的 xml 布局制作一个虚拟活动。然后,您可以打开此虚拟活动,以编程方式截取屏幕截图并使用此库将该图像转换为 pdf 。当然也有一些限制,比如不能滚动,不能超过一页,但对于有限的应用程序来说,这是快速而简单的。希望这可以帮助某人!

回答by DenisMath

It's not easy to find a full solution of the problem of a convertion of an arbitrary HTML to PDF with non-english letters in Android. I test it for russian unicode letters.

在Android中找到将任意HTML转换为带有非英文字母的PDF问题的完整解决方案并不容易。我测试它的俄语unicode字母。

We use three libraries:

我们使用三个库:

(1) Jsoup(jsoup-1.7.3.jar) for a convertion from HTML to XHTML,

(1) Jsoup(jsoup-1.7.3.jar) 用于从 HTML 到 XHTML 的转换,

(2) iTextPDF(itextpdf-5.5.0.jar),

(2) iTextPDF(itextpdf-5.5.0.jar),

(3) XMLWorker(xmlworker-5.5.1.jar).

(3) XMLWorker(xmlworker-5.5.1.jar)。

public boolean createPDF(String rawHTML, String fileName, ContextWrapper context){
    final String APPLICATION_PACKAGE_NAME = context.getBaseContext().getPackageName();
    File path = new File( Environment.getExternalStorageDirectory(), APPLICATION_PACKAGE_NAME );
    if ( !path.exists() ){ path.mkdir(); }
    File file = new File(path, fileName);

    try{

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
    document.open();

    // Подготавливаем HTML
    String htmlText = Jsoup.clean( rawHTML, Whitelist.relaxed() );
    InputStream inputStream = new ByteArrayInputStream( htmlText.getBytes() );

    // Печатаем документ PDF
    XMLWorkerHelper.getInstance().parseXHtml(writer, document,
        inputStream, null, Charset.defaultCharset(), new MyFont());

    document.close();
    return true;

    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;
    } catch (DocumentException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } 

The difficult problem is to display russian letters in PDF by using iTextPDF XMLWorker library. For this we should create our own implementation of FontProvider interface:

困难的问题是使用 iTextPDF XMLWorker 库在 PDF 中显示俄文字母。为此,我们应该创建自己的 FontProvider 接口实现:

public class MyFont implements FontProvider{
    private static final String FONT_PATH = "/system/fonts/DroidSans.ttf";
    private static final String FONT_ALIAS = "my_font";

    public MyFont(){ FontFactory.register(FONT_PATH, FONT_ALIAS); }

    @Override
    public Font getFont(String fontname, String encoding, boolean embedded,
        float size, int style, BaseColor color){

        return FontFactory.getFont(FONT_ALIAS, BaseFont.IDENTITY_H, 
            BaseFont.EMBEDDED, size, style, color);
    }

    @Override
    public boolean isRegistered(String name) { return name.equals( FONT_ALIAS ); }
}

Here we use the standard Android font Droid Sans, which is located in the system folder:

这里我们使用标准的 Android 字体 Droid Sans,它位于系统文件夹中:

private static final String FONT_PATH = "/system/fonts/DroidSans.ttf";

回答by Angelo

A bit late and I have not yet tested it yet myself but another library that is under the BSD licenseis Android PDF Writer.

有点晚了,我还没有自己测试过,但另一个在BSD 许可下的库是Android PDF Writer

UpdateI have tried the library myself. Works ok with simple pdf generations (it provide methods for adding text, lines, rectangles, bitmaps, fonts). The only problem is that the generated PDF is stored in a String in memory, this may cause memory issues in large documents.

更新我自己尝试过图书馆。适用于简单的 pdf 生成(它提供添加文本、线条、矩形、位图、字体的方法)。唯一的问题是生成的PDF在内存中存储在一个字符串中,这可能会导致大文档中的内存问题。

回答by IcedDante

PDFJetoffers an open-source version of their library that should be able to handle any basic PDF generation task. It's a purely Java-based solution and it is stated to be compatible with Android. There is a commercial version with some additional features that does not appear to be too expensive.

PDFJet提供了他们库的开源版本,应该能够处理任何基本的 PDF 生成任务。这是一个纯粹基于 Java 的解决方案,据说它与 Android 兼容。有一个带有一些附加功能的商业版本,看起来并不太贵。

回答by Johnny Doe

U can also use PoDoFolibrary. The main goal is that it published under LGPL. Since it is written in C++ you should cross-compile it using NDK and write C-side and Java wrapper. Some of third-party libraries can be used from OpenCVproject. Also in OpenCV project U can find android.toolchain.cmakefile, which will help you with generating Makefile.

你也可以使用PoDoFo库。主要目标是它在 LGPL 下发布。由于它是用 C++ 编写的,因此您应该使用 NDK 交叉编译它并编写 C 端和 Java 包装器。一些第三方库可以从OpenCV项目中使用。同样在 OpenCV 项目中android.toolchain.cmake,您可以找到文件,这将帮助您生成Makefile.

回答by Paul Jowett

Late, but relevant to request and hopefully helpful. If using an external service (as suggested in the reply by CommonsWare) then Docmosishas a cloud service that might help - offloading processing to a cloud service that does the heavy processing. That approach is ideal in some circumstances but of course relies on being net-connected.

晚了,但与请求相关,希望有帮助。如果使用外部服务(如 CommonsWare 的答复中所建议),则Docmosis有一个云服务可能会有所帮助 - 将处理卸载到执行繁重处理的云服务。这种方法在某些情况下是理想的,但当然依赖于网络连接。