Generate PDF from HTML String in Android or Convert HTML to PDF using Webview in Android.

1) Create a package in your App Java folder with the name android.print

2) In that package create PdfConverter class.

package android.print;

import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class PdfConverter implements Runnable {

    private static final String TAG = "PdfConverter";
    private static PdfConverter sInstance;

    private Context mContext;
    private String mHtmlString;
    private File mPdfFile;
    private PrintAttributes mPdfPrintAttrs;
    private boolean mIsCurrentlyConverting;
    private WebView mWebView;
    OnPDFCreated mOnPDFCreated;

    private PdfConverter() {

    public static synchronized PdfConverter getInstance() {
        if (sInstance == null)
            sInstance = new PdfConverter();

        return sInstance;

    public void SetOnPDFCreatedListener(OnPDFCreated OnPDFCreated) {
        this.mOnPDFCreated = OnPDFCreated;

    public void run() {
        mWebView = new WebView(mContext);


        mWebView.setWebViewClient(new WebViewClient() {
            public void onPageFinished(WebView view, String url) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
                    throw new RuntimeException("call requires API level 19");
                else {
                    PrintDocumentAdapter documentAdapter = null;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        documentAdapter = mWebView.createPrintDocumentAdapter("Document");
                    }else {
                        documentAdapter = mWebView.createPrintDocumentAdapter();

                    documentAdapter.onLayout(null, getPdfPrintAttrs(), null, new PrintDocumentAdapter.LayoutResultCallback() {
                    }, null);
                    documentAdapter.onWrite(new PageRange[]{PageRange.ALL_PAGES}, getOutputFileDescriptor(), null, new PrintDocumentAdapter.WriteResultCallback() {
                        public void onWriteFinished(PageRange[] pages) {
                            Log.e("onWriteFinished", "onWriteFinished call");
                            if (mOnPDFCreated != null){

        mWebView.loadDataWithBaseURL("",mHtmlString, "text/HTML", "UTF-8","");

    private PrintAttributes getPdfPrintAttrs() {
        return mPdfPrintAttrs != null ? mPdfPrintAttrs : getDefaultPrintAttrs();

    public void setPdfPrintAttrs(PrintAttributes printAttrs) {
        this.mPdfPrintAttrs = printAttrs;

    public void convert(Context context, String htmlString, File file) {
        if (context == null)
            throw new IllegalArgumentException("context can't be null");
        if (htmlString == null)
            throw new IllegalArgumentException("htmlString can't be null");
        if (file == null)
            throw new IllegalArgumentException("file can't be null");

        if (mIsCurrentlyConverting)

        mContext = context;
        mHtmlString = htmlString;
        mPdfFile = file;
        mIsCurrentlyConverting = true;

    private ParcelFileDescriptor getOutputFileDescriptor() {
        try {
            return, ParcelFileDescriptor.MODE_TRUNCATE | ParcelFileDescriptor.MODE_READ_WRITE);
        } catch (Exception e) {
            Log.d(TAG, "Failed to open ParcelFileDescriptor", e);
        return null;

    private PrintAttributes getDefaultPrintAttrs() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return null;

        return new PrintAttributes.Builder()
                .setResolution(new PrintAttributes.Resolution("RESOLUTION_ID", "RESOLUTION_ID", 600, 600))


    private void runOnUiThread(Runnable runnable) {
        Handler handler = new Handler(mContext.getMainLooper());;

    private void destroy() {
        mContext = null;
        mHtmlString = null;
        mPdfFile = null;
        mPdfPrintAttrs = null;
        mIsCurrentlyConverting = false;
        mWebView = null;

    public interface OnPDFCreated {

        void onPDFCreated();



       YourFilePath Example:-

     /storage/emulated/0/PDF Example/Example_PDF_File.pdf

       PdfConverter converter = PdfConverter.getInstance();
                converter.convert(this, YourHTMLString,
                        new File(YourFilePath);

                converter.SetOnPDFCreatedListener(new OnPDFCreated() {

                    public void OnPDFCreated() {
                                // Here you can open the PDF file.



Post a Comment

Popular posts from this blog

Android Studio 3.5 or above usb device not detected in Android Studio or Unable to detect adb version, exit value: 0xc0000135. ADB depends on the Windows Universal C Runtime, which is usually installed by default via Windows Update. You may need to manually fetch and install the runtime package here:

Lint found fatal errors while assembling a release target.

ViewModelProviders.of(this) is deprecated what to use instead ViewModelProviders.of(this) OR if you don't want to use ViewmodelFactory OR ViewModelProviders error.