问题
I am trying to create an PDF using android.graphics.pdf. My issue is with multiple pages. I can give android.graphics.pdf html which could be then printed to a PDF. Now that doesn't work if text overflows the set page size. Is it possible to give it all the html and it would create multiple pages according to the content with respect to the page size? As does TCPDF :)
Note. I am trying to avoid creating separate multiple pages by calculating the height of the content.
回答1:
For this you'll need to add the jar of iTextG to your project:
public void createandDisplayPdf(String text) {
Document doc = new Document();
try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Dir";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, "newFile.pdf");
FileOutputStream fOut = new FileOutputStream(file);
PdfWriter.getInstance(doc, fOut);
//open the document
doc.open();
Paragraph p1 = new Paragraph(text);
Font paraFont= new Font(Font.COURIER);
p1.setAlignment(Paragraph.ALIGN_CENTER);
p1.setFont(paraFont);
//add paragraph to document
doc.add(p1);
} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
}
finally {
doc.close();
}
viewPdf("newFile.pdf", "Dir");
}
// Method for opening a pdf file
private void viewPdf(String file, String directory) {
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/" + directory + "/" + file);
Uri path = Uri.fromFile(pdfFile);
// Setting the intent for pdf reader
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(TableActivity.this, "Can't read pdf file", Toast.LENGTH_SHORT).show();
}
}
来源:https://stackoverflow.com/questions/42158792/creating-multiple-pages-of-pdf-using-android-graphics-pdf