【问题标题】:How to draw text in multiple line in multiple pages using static layout for PDF Creation如何使用静态布局在多页中绘制多行文本以创建 PDF
【发布时间】:2021-08-03 11:18:36
【问题描述】:

我正在使用下面的代码来绘制文本并以 PDF 格式书写,但它无法在多个页面中绘制?解决这个问题的最佳方法是什么。

 PdfDocument document = new PdfDocument();
        PdfDocument.PageInfo pageInfo = new
                PdfDocument.PageInfo.Builder(pageWidth, pageheight, 3).create();
        PdfDocument.Page page = document.startPage(pageInfo);
        Canvas canvas = page.getCanvas();


            TextPaint paint=new TextPaint(Paint.ANTI_ALIAS_FLAG);
            paint.setColor(Color.rgb(0, 0, 0));
            paint.setTextSize((int) (7 * 2));
            paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);

            int textWidth = canvas.getWidth() - (int) (16 * 2);

            StaticLayout textLayout = new StaticLayout(
                    edittextContent.getText().toString(), paint, pageWidth-50, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);

            int textHeight = textLayout.getHeight();

            float x = ((pageWidth-15) - textWidth)/2;
            float y = ((pageheight-15) - textHeight)/2;

            // draw text to the Canvas center
            canvas.save();
            canvas.translate(15, 10);
            textLayout.draw(canvas);
            canvas.restore();

        document.finishPage(page);
        document.writeTo(fOut);
        document.close();

【问题讨论】:

    标签: android pdf itext pdf-generation staticlayout


    【解决方案1】:

    我假设您使用的是原生 android android.graphics.pdf.PdfDocument。看起来它只提供了将文本行放置在特定页面上特定坐标处的低级功能。如果您想坚持使用此 API,您可能需要为要在文档中创建的每个页面调用 startPage()finishPage(),并为每个页面准备拆分内容。像这样的:

    // start 1st page
    PdfDocument.Page page = document.startPage(pageInfo);
    // draw something on the page
    // finish 1st page
    document.finishPage(page);
    
    // start 2nd page
    PdfDocument.Page page = document.startPage(pageInfo);
    // draw something on the page
    // finish 2nd page
    document.finishPage(page);
    
    ...
    

    如果您想要更高级的功能,如果内容不合适,会跨越多个页面,您需要使用其他一些工具。

    例如你可以试试iText7库:

    PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
    Document document = new Document(pdf, new PageSize(pageWidth, pageheight));
    // set here any amount of text, it will span across multiple pages if needed
    String text = ...;
    document.add(new Paragraph(line));
    document.close();
    

    更多示例请参见https://kb.itextpdf.com/home/it7kb/ebooks/itext-7-building-blocks/chapter-2-adding-content-to-a-canvas-or-a-document

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-07
      • 2014-07-08
      相关资源
      最近更新 更多