Created
July 12, 2016 07:23
-
-
Save tejpratap46/813171d2788906cbcc67905b83249e2b to your computer and use it in GitHub Desktop.
print a simple webview android
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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