该工具类方法实现了调用原生打印机打印PDF文件,打印HTML格式文件;打印HTML文件如果较大的话,生成预览比较慢,所以还有个方法将HTML文件转换为PDF,然后打印,此方法与原生PDF打印生成预览时间差不多,但是可能会造成内存溢出,但不影响使用。
import android.app.Activity;
import android.content.Context;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintManager;
import android.util.Base64;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.FontProvider;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
public class PrintUtil {
/**
* 打印pdf文件方法
*
* @param activity
* @throws IOException
*/
public static void printpdf(Activity activity) throws IOException {
PrintManager printManager = (PrintManager) activity.getSystemService(Context.PRINT_SERVICE);
MyPrintPdfAdapter myPrintAdapter = new MyPrintPdfAdapter(readStream(1));
PrintAttributes.Builder builder = new PrintAttributes.Builder();
builder.setColorMode(PrintAttributes.COLOR_MODE_COLOR);
printManager.print("test", myPrintAdapter, builder.build());
}
/**
* 打印html文件方法
*
* @param activity
* @throws IOException
*/
public static void printWebView(Activity activity) throws IOException {
WebView webView = new WebView(activity);
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
@Override
public void