1

I have a notebook app and i want to have the notes to be saved as PDF files. the user can write long texts in TextView but when i get the text to string and create a PDF file, only a small part of the text in a single line will be in the PDF file. how can i break the text to multiple lines to see entire text in PDF page? i used this part of java codes to break the text but it does not work.

     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);
  • While this solves the problem of multiline using StaticLayout but if the text size is very long and requires multi pages then please [check my answer](https://stackoverflow.com/a/71394812/12552434) where I have explained with sample code how to handle it. https://stackoverflow.com/a/71394812/12552434 – abby Mar 08 '22 at 12:17

1 Answers1

4

I had the same problem. I managed to solve it from this post. it uses static layout. Below is my whole code which saves a string value to a pdf file created with multiline breaks.

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();

If your string is still overflowing the page, try different values here

canvas.getWidth() - 100

in StaticLayout initialization. I will provide some before and after screenshots.

before multiline breaks

after multiline breaks

AkiraZombie
  • 56
  • 1
  • 4
  • If the text is very long it should create next page in pdf but with the above code it overflows below, any idea how to resolve this? – abby Mar 06 '22 at 02:41