How to create PDFs in an Android app?

AndroidPdf

Android Problem Overview


Is there any way to create PDF Files from an Android application?

Android Solutions


Solution 1 - Android

If anyone wants to generate PDFs on Android device, here is how to do it:

Solution 2 - Android

If you are developing for devices with API level 19 or higher you can use the built in PrintedPdfDocument: http://developer.android.com/reference/android/print/pdf/PrintedPdfDocument.html

// open a new document
PrintedPdfDocument document = new PrintedPdfDocument(context,
     printAttributes);

// start a page
Page page = document.startPage(0);

// draw something on the page
View content = getContentView();
content.draw(page.getCanvas());

// finish the page
document.finishPage(page);
. . .
// add more pages
. . .
// write the document content
document.writeTo(getOutputStream());

//close the document
document.close();

Solution 3 - Android

A trick to make a PDF with complex features is to make a dummy activity with the desired xml layout. You can then open this dummy activity, take a screenshot programmatically and convert that image to pdf using this library. Of course there are limitations such as not being able to scroll, not more than one page,but for a limited application this is quick and easy. Hope this helps someone!

Solution 4 - Android

It's not easy to find a full solution of the problem of a convertion of an arbitrary HTML to PDF with non-english letters in Android. I test it for russian unicode letters.

We use three libraries:

(1) Jsoup (jsoup-1.7.3.jar) for a convertion from HTML to XHTML,

(2) iTextPDF (itextpdf-5.5.0.jar),

(3) XMLWorker (xmlworker-5.5.1.jar).

public boolean createPDF(String rawHTML, String fileName, ContextWrapper context){
    final String APPLICATION_PACKAGE_NAME = context.getBaseContext().getPackageName();
    File path = new File( Environment.getExternalStorageDirectory(), APPLICATION_PACKAGE_NAME );
	if ( !path.exists() ){ path.mkdir(); }
	File file = new File(path, fileName);
	 
	try{

 	Document document = new Document();
 	PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
	document.open();
		
	// Подготавливаем HTML
	String htmlText = Jsoup.clean( rawHTML, Whitelist.relaxed() );
	InputStream inputStream = new ByteArrayInputStream( htmlText.getBytes() );
		
	// Печатаем документ PDF
	XMLWorkerHelper.getInstance().parseXHtml(writer, document,
	    inputStream, null, Charset.defaultCharset(), new MyFont());
					
	document.close();
	return true;
		
	} catch (FileNotFoundException e) {
		e.printStackTrace();
		return false;
	} catch (DocumentException e) {
		e.printStackTrace();
		return false;
	} catch (IOException e) {
		e.printStackTrace();
		return false;
	} 

The difficult problem is to display russian letters in PDF by using iTextPDF XMLWorker library. For this we should create our own implementation of FontProvider interface:

public class MyFont implements FontProvider{
    private static final String FONT_PATH = "/system/fonts/DroidSans.ttf";
    private static final String FONT_ALIAS = "my_font";

    public MyFont(){ FontFactory.register(FONT_PATH, FONT_ALIAS); }

	@Override
	public Font getFont(String fontname, String encoding, boolean embedded,
        float size, int style, BaseColor color){
		
		return FontFactory.getFont(FONT_ALIAS, BaseFont.IDENTITY_H, 
            BaseFont.EMBEDDED, size, style, color);
	}

	@Override
	public boolean isRegistered(String name) { return name.equals( FONT_ALIAS ); }
}

Here we use the standard Android font Droid Sans, which is located in the system folder:

private static final String FONT_PATH = "/system/fonts/DroidSans.ttf";

Solution 5 - Android

A bit late and I have not yet tested it yet myself but another library that is under the BSD license is Android PDF Writer.

Update I have tried the library myself. Works ok with simple pdf generations (it provide methods for adding text, lines, rectangles, bitmaps, fonts). The only problem is that the generated PDF is stored in a String in memory, this may cause memory issues in large documents.

Solution 6 - Android

PDFJet offers an open-source version of their library that should be able to handle any basic PDF generation task. It's a purely Java-based solution and it is stated to be compatible with Android. There is a commercial version with some additional features that does not appear to be too expensive.

Solution 7 - Android

Late, but relevant to request and hopefully helpful. If using an external service (as suggested in the reply by CommonsWare) then Docmosis has a cloud service that might help - offloading processing to a cloud service that does the heavy processing. That approach is ideal in some circumstances but of course relies on being net-connected.

Solution 8 - Android

U can also use PoDoFo library. The main goal is that it published under LGPL. Since it is written in C++ you should cross-compile it using NDK and write C-side and Java wrapper. Some of third-party libraries can be used from OpenCV project. Also in OpenCV project U can find android.toolchain.cmake file, which will help you with generating Makefile.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser299908View Question on Stackoverflow
Solution 1 - Androidnikib3roView Answer on Stackoverflow
Solution 2 - Androidteh.fonsiView Answer on Stackoverflow
Solution 3 - AndroidhrishitiwariView Answer on Stackoverflow
Solution 4 - AndroidDenisMathView Answer on Stackoverflow
Solution 5 - AndroidAngeloView Answer on Stackoverflow
Solution 6 - AndroidIcedDanteView Answer on Stackoverflow
Solution 7 - AndroidPaul JowettView Answer on Stackoverflow
Solution 8 - AndroidJohnny DoeView Answer on Stackoverflow