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.
}
});
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.
}
});
Excellent idea!!! I really enjoyed reading your post. Thank you for your efforts . Share more like this.
ReplyDeleteJava Training in Velachery
Java training in Anna Nagar
Java course in Tambaram
Graphic Design Courses in Porur
Hadoop Training in T Nagar
RPA Training in OMR
Android Training in Chennai
PHP Training in Chennai
Dot Net Training in T Nagar
PHP Training in Anna Nagar
Well Done...! it is very comprehensive and keeps updating here...
ReplyDeleteReactJS Training in Chennai
ReactJS Course in Chennai
PlC Training in Chennai
Useful and well explained on HTML to PDF Converter.
ReplyDeleteThanks for sharing keeps updating more....
Thanks, this work. you save my day.
ReplyDeleteNice ! But image not showing, can you solve this please ???
ReplyDeleteThe Eight-Wheel Classic - TITIAN Arts
ReplyDeleteThe eight-wheel 메이피로출장마사지 classic bicycle is titanium flat iron available in six sizes. The Bicycle Wheel is https://deccasino.com/review/merit-casino/ a classic https://vannienailor4166blog.blogspot.com/ bicycle made in หาเงินออนไลน์ USA, but there are three variations in