Skip to content

Instantly share code, notes, and snippets.

@tejpratap46
Created July 12, 2016 07:23
Show Gist options
  • Save tejpratap46/813171d2788906cbcc67905b83249e2b to your computer and use it in GitHub Desktop.
Save tejpratap46/813171d2788906cbcc67905b83249e2b to your computer and use it in GitHub Desktop.
print a simple webview android
webView.loadData(html, "text/html", "UTF-8");
private void print(WebView webView) {
try {
// PrintManager
String PRINT_SERVICE = (String) Context.class.getDeclaredField(
"PRINT_SERVICE").get(null);
Object printManager = this.getSystemService(PRINT_SERVICE);
// PrintDocumentAdapter
Class<?> printDocumentAdapterClass = Class
.forName("android.print.PrintDocumentAdapter");
Method createPrintDocumentAdapterMethod = webView.getClass()
.getMethod("createPrintDocumentAdapter");
Object printAdapter = createPrintDocumentAdapterMethod
.invoke(webView);
// PrintAttributes
Class<?> printAttributesBuilderClass = Class
.forName("android.print.PrintAttributes$Builder");
Constructor<?> ctor = printAttributesBuilderClass.getConstructor();
Object printAttributes = ctor.newInstance(new Object[] {});
Method buildMethod = printAttributes.getClass().getMethod("build");
Object printAttributesBuild = buildMethod.invoke(printAttributes);
// PrintJob
String jobName = "My Document";
Method printMethod = printManager.getClass().getMethod("print",
String.class, printDocumentAdapterClass,
printAttributesBuild.getClass());
Object printJob = printMethod.invoke(printManager, jobName,
printAdapter, printAttributesBuild);
} catch (Exception e) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment