簡體   English   中英

如何在 android 中創建 PDF 中的長文本到多行?

[英]how to break a long text to multiple lines in PDF creation in android?

我有一個筆記本應用程序,我想將筆記保存為 PDF 文件。 用戶可以在 TextView 中寫入長文本,但是當我將文本轉換為字符串並創建 PDF 文件時,單行中只有一小部分文本將在 PDF 文件中如何將文本分成多行以查看 PDF 頁面中的整個文本? 我使用這部分 java 代碼來破壞文本,但它不起作用。

     textView = findViewById(R.id.textView);

     String pdfText = textView.getText().toString();

     Paint contentPaint = new Paint();
        int length = pdfText.length();
        contentPaint.breakText(pdfText, 0, length, true, 70, null);
        canvas.drawText(pdfText, 30, 285, contentPaint);

我有同樣的問題。 我設法從這篇文章中解決了這個問題。 它使用 static 布局。 下面是我的整個代碼,它將字符串值保存到使用多行換行符創建的 pdf 文件中。

String saveFilePath = path.getPath();
String textToSave = detectedText.getText().toString();
File file = new File(path, filenameString + ".pdf");
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(595, 842, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();

//*this part i took from the post for multiline breaks*
TextPaint mTextPaint = new TextPaint();
StaticLayout mTextLayout = new StaticLayout( textToSave ,mTextPaint, canvas.getWidth() - 100, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
canvas.save();
int textX = 50;
int textY = 50;
canvas.translate(textX, textY);
//**

mTextLayout.draw(canvas);
canvas.restore();
document.finishPage(page);
document.writeTo(fOut);
document.close();

如果您的字符串仍然溢出頁面,請在此處嘗試不同的值

canvas.getWidth() - 100

在 StaticLayout 初始化中。 我將提供一些前后截圖。

在多行換行符之前

多行中斷后

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM