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;
import java.io.File;

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;
    }

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

        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setAppCacheEnabled(true);
        mWebView.getSettings().setLoadsImagesAutomatically(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            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() {
                        @Override
                        public void onWriteFinished(PageRange[] pages) {
                            Log.e("onWriteFinished", "onWriteFinished call");
                            if (mOnPDFCreated != null){
                                mOnPDFCreated.onPDFCreated();
                            }
                            destroy();
                        }
                    });
                }
            }
        });

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

        mContext = context;
        mHtmlString = htmlString;
        mPdfFile = file;
        mIsCurrentlyConverting = true;
        runOnUiThread(this);
    }

    private ParcelFileDescriptor getOutputFileDescriptor() {
        try {
            mPdfFile.createNewFile();
            return ParcelFileDescriptor.open(mPdfFile, 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()
                .setMediaSize(PrintAttributes.MediaSize.NA_GOVT_LETTER)
                .setResolution(new PrintAttributes.Resolution("RESOLUTION_ID", "RESOLUTION_ID", 600, 600))
                .setMinMargins(PrintAttributes.Margins.NO_MARGINS)
                .build();

    }

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

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


    public interface OnPDFCreated {

        void onPDFCreated();

    }

}


3)
       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() {

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

                     
                    }
                }); 

Comments

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: https://support.microsoft.com/en-ca/help/2999226/update-for-universal-c-runtime-in-windows

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.