如何在android中使用PdfDocument从具有适当多行和多页的长字符串生成Pdf?

发布于 2025-01-11 06:34:59 字数 206 浏览 0 评论 0原文

我有一个很长的字符串,它可能是连续的,没有空格,也可能不连续,如果需要,它应该自动生成多页的 pdf,并使用 PdfDocument 生成适当的多行。

我首先尝试使用油漆,但只打印了一行文本溢出的内容。使用 StaticLayout 解决了这个问题,并获得了正确的多行,但现在文本从下面溢出。

我搜索了很多,但没有确切找到一个,而且我不想将 iText 仅用于开源项目。

I have a very long string which may be continuous without space or not continuous, and it should automatically generate pdf with with multiple pages if necessary and with proper multiline with PdfDocument.

I have tried firstly using paint but only one line with text overflowing was being printed. This problem was solved using StaticLayout and proper multiline is got but now the text gets overflown from below.

I have searched a lot but didn't exactly find one and I don't want to use iText as its only for opensource projects.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡紫姑娘! 2025-01-18 06:34:59

这个解决方案通过使用简单的 PdfDocument 和 StaticLayout 解决了问题,而不使用任何外部付费库。我在问题中分享的问题是在生成的 pdf 文件中保持文本的正确结构。

我使用 A4 尺寸页面的长度和宽度,并将每页中的字符数固定为限制,之后当遇到该行末尾时,它会自动创建下一页,自动下一行也由 StaticLayout 处理可以看到文字溢出。

如果您觉得可以尝试为每个页面设置不同的字符限制,并根据需要尝试不同的大小。您还可以尝试 Android 版本 Q/29 及以上版本(不低于其版本)支持的 StaticLayout.Builder

我将与您分享的代码示例,如果您使用该代码示例,无论您的文本有多长,如果文本很长,它都会自动处理多页并生成pdf,并且它还会维护段落等,您还可以自定义页面形状、字符数等根据您的需要。代码中的其他细节是不言自明的。

 String text = "Lorem ipsum...very long text";
 ArrayList<String> texts = new ArrayList<>();
    int tot_char_count = 0;
    //Counts total characters in the long text
    for (int i = 0; i < text.length(); i++) {
        tot_char_count++;
    }
    int per_page_words = 4900;
    int pages = tot_char_count / per_page_words;
    int remainder_pages_extra = tot_char_count % per_page_words;
    if (remainder_pages_extra > 0) {
        pages++;
    }
    int k = pages, count = 0;
    while (k != 0) {
        StringBuilder each_page_text = new StringBuilder();
        for (int y = 0; y < per_page_words; y++) {
            if (count < tot_char_count) {
                each_page_text.append(text.charAt(count));
                if (y == (per_page_words - 1) && text.charAt(count) != ' ') {
                    while (text.charAt(count) != '\n') {
                        count++;
                        each_page_text.append(text.charAt(count));
                    }
                } else {
                    count++;
                }
            }
        }
        texts.add(each_page_text.toString());
        k--;
    }

    PdfDocument pdfDocument = new PdfDocument();
    int pageNumber = 0;
    try {
        pageNumber++;
        for (String each_page_text : texts) {
            PdfDocument.PageInfo mypageInfo = new PdfDocument.PageInfo.Builder(595, 842, pageNumber).create();
            PdfDocument.Page myPage = pdfDocument.startPage(mypageInfo);
            Canvas canvas = myPage.getCanvas();
            TextPaint mTextPaint = new TextPaint();
            mTextPaint.setTextSize(11);
            mTextPaint.setTypeface(ResourcesCompat.getFont(context, R.font.roboto));               
            StaticLayout mTextLayout = new StaticLayout(each_page_text, mTextPaint, canvas.getWidth() - 60, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);               
            canvas.save();
            int textX = 30;
            int textY = 30;
            canvas.translate(textX, textY);
            mTextLayout.draw(canvas);
            canvas.restore();
            pdfDocument.finishPage(myPage);
        }            
        File file = new File(context.getFilesDir(), "GeneratedFile.pdf");
        FileOutputStream fOut = new FileOutputStream(file);
        pdfDocument.writeTo(fOut);
        //  Toast.makeText(context, "PDF file generated successfully.", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {          
        e.printStackTrace();
    }
    pdfDocument.close();

This solution by which I solved the problem by using simple PdfDocument and StaticLayout without using any external paid libraries. The problem as I have shared in my question is that maintaining proper structure of the texts in the generated pdf file.

I used the length and width of a A4 size page and have fixed the number of characters in each page to a limit, after that when it encounters the end of that line it automatically creates next page, also auto next line is handled by StaticLayout no overflowing of text is seen.

If you feel you can try with different character limit for each page and try different size as your need. Also you can try the StaticLayout.Builder which is supported in Android version Q/29 and above not below it.

The code sample I will share with you, which if you use, no matter how long the text you have, it will automatically handle multi page if text is long and generate the pdf, also it maintains paragraphs etc, you can also customise page shape, number of characters etc according to your need. Other details in the code are self-explanatory.

 String text = "Lorem ipsum...very long text";
 ArrayList<String> texts = new ArrayList<>();
    int tot_char_count = 0;
    //Counts total characters in the long text
    for (int i = 0; i < text.length(); i++) {
        tot_char_count++;
    }
    int per_page_words = 4900;
    int pages = tot_char_count / per_page_words;
    int remainder_pages_extra = tot_char_count % per_page_words;
    if (remainder_pages_extra > 0) {
        pages++;
    }
    int k = pages, count = 0;
    while (k != 0) {
        StringBuilder each_page_text = new StringBuilder();
        for (int y = 0; y < per_page_words; y++) {
            if (count < tot_char_count) {
                each_page_text.append(text.charAt(count));
                if (y == (per_page_words - 1) && text.charAt(count) != ' ') {
                    while (text.charAt(count) != '\n') {
                        count++;
                        each_page_text.append(text.charAt(count));
                    }
                } else {
                    count++;
                }
            }
        }
        texts.add(each_page_text.toString());
        k--;
    }

    PdfDocument pdfDocument = new PdfDocument();
    int pageNumber = 0;
    try {
        pageNumber++;
        for (String each_page_text : texts) {
            PdfDocument.PageInfo mypageInfo = new PdfDocument.PageInfo.Builder(595, 842, pageNumber).create();
            PdfDocument.Page myPage = pdfDocument.startPage(mypageInfo);
            Canvas canvas = myPage.getCanvas();
            TextPaint mTextPaint = new TextPaint();
            mTextPaint.setTextSize(11);
            mTextPaint.setTypeface(ResourcesCompat.getFont(context, R.font.roboto));               
            StaticLayout mTextLayout = new StaticLayout(each_page_text, mTextPaint, canvas.getWidth() - 60, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);               
            canvas.save();
            int textX = 30;
            int textY = 30;
            canvas.translate(textX, textY);
            mTextLayout.draw(canvas);
            canvas.restore();
            pdfDocument.finishPage(myPage);
        }            
        File file = new File(context.getFilesDir(), "GeneratedFile.pdf");
        FileOutputStream fOut = new FileOutputStream(file);
        pdfDocument.writeTo(fOut);
        //  Toast.makeText(context, "PDF file generated successfully.", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {          
        e.printStackTrace();
    }
    pdfDocument.close();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文