概述
该工具类方法实现了调用原生打印机打印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 onPageFinished(WebView view, String url) {
createWebPrintJob(view, activity);
}
});
String htmlDocument = readStream(2);
webView.loadDataWithBaseURL(null, htmlDocument, "text/HTML", "UTF-8", null);
}
private static void createWebPrintJob(WebView webView, Activity activity) {
PrintManager printManager = (PrintManager) activity.getSystemService(Context.PRINT_SERVICE);
PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter();
String jobName = "webDocument";
printManager.print(jobName, printAdapter, new PrintAttributes.Builder().build());
}
/**
* 读取本地文件
* @param type
* @return
* @throws IOException
*/
public static String readStream(int type) throws IOException {
String filePath = "/sdcard/1.html";
if (type == 1) {
filePath = "/sdcard/doc.pdf";
}
FileInputStream fileInputStream = new FileInputStream(filePath);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len = 0;
while (-1 != (len = fileInputStream.read(bytes))) {
byteArrayOutputStream.write(bytes, 0, len);
}
byteArrayOutputStream.close();
fileInputStream.close();
byte[] resBytes = byteArrayOutputStream.toByteArray();
if (type == 1) {
return Base64.encodeToString(resBytes, 1);
} else {
return new String(resBytes, "UTF-8");
}
}
//===========================================================================================================
/**
*将HTML数据转换成PDF文件存在本地
* 此方法需要引入:itextpdf-5.5.jar,jsoup-1.7.jar,xmlworker-5.3.5-javadoc.jar,xmlworker-5.5.6.jar
* @param rawHTML
* @param fileName
* @param context
* @return
*/
public String createPDF(String rawHTML, String fileName, Context context) {
File file = new File(fileName);
try {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
document.open();
// HTML
String htmlText = Jsoup.clean(rawHTML, Whitelist.relaxed());
InputStream inputStream = new ByteArrayInputStream(htmlText.getBytes());
// PDF
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
inputStream, null, Charset.defaultCharset(), new MyFont(context));
document.close();
return "";
} catch (FileNotFoundException e) {
e.printStackTrace();
return "Error|" + e.getMessage();
} catch (DocumentException e) {
e.printStackTrace();
return "Error|" + e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "Error|" + e.getMessage();
}
}
public class MyFont implements FontProvider {
private static final String FONT_PATH = "/sdcard/DroidSansFallback.ttf";
private static final String FONT_ALIAS = "my_font";
public MyFont(Context context) {
copyTTFtoSdcard(context);
FontFactory.register(FONT_PATH, FONT_ALIAS);
}
@Override
public Font getFont(String fontname, String encoding, boolean embedded,
float size, int style, BaseColor color) {
return FontFactory.getFont(FONT_ALIAS, BaseFont.IDENTITY_H,
BaseFont.EMBEDDED, size, style, color);
}
@Override
public boolean isRegistered(String name) {
return name.equals(FONT_ALIAS);
}
}
private void copyTTFtoSdcard(Context context) {
File file = new File("/sdcard/DroidSansFallback.ttf");
if (file.exists()) {
return;
}
InputStream open = null;
FileOutputStream fileOutputStream = null;
try {
open = context.getAssets().open("DroidSansFallback.ttf");
fileOutputStream = new FileOutputStream(file);
byte[] bytes = new byte[1024];
int len;
while ((len = open.read(bytes)) > 0) {
fileOutputStream.write(bytes, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (open != null) {
open.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
MyPrintPdfAdapter 类
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.print.PageRange;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintDocumentInfo;
import android.util.Base64;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MyPrintPdfAdapter extends PrintDocumentAdapter {
// private String mFilePath;
private String fileBaseString;
// public MyPrintPdfAdapter(String file) {
// this.mFilePath = file;
// }
public MyPrintPdfAdapter(String fileBase64Str){
this.fileBaseString = fileBase64Str;
}
// 当用户更改打印设置导致打印结果改变时调用,如更改纸张尺寸,纸张方向等;
@Override
public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal,
LayoutResultCallback callback, Bundle extras) {
if (cancellationSignal.isCanceled()) {
callback.onLayoutCancelled();
return;
}
PrintDocumentInfo info = new PrintDocumentInfo.Builder(getJobName())
.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
.build();
callback.onLayoutFinished(info, true);
}
// 当将要打印的结果写入到文件中时调用,该方法在每次onLayout()调用后会调用一次或多次;
@Override
public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal,
WriteResultCallback callback) {
InputStream input = null;
OutputStream output = null;
try {
byte[] fileByte = Base64.decode(fileBaseString, Base64.DEFAULT);
input = new ByteArrayInputStream(fileByte);
output = new FileOutputStream(destination.getFileDescriptor());
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});
} catch (FileNotFoundException e) {
// Catch exception
e.printStackTrace();
} catch (Exception e) {
// Catch exception
e.printStackTrace();
} finally {
try {
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* @return
*/
private String getJobName() {
try {
// String[] filePaths = mFilePath.split(File.separator);
// return filePaths[filePaths.length - 1];
return "receiptPrint";
} catch (Exception e) {
e.printStackTrace();
}
return String.valueOf(System.currentTimeMillis());
}
}
注意:
1.在“将HTML数据转换成PDF文件”方法中,需要用到“DroidSansFallback.ttf”字体,一般此字体在安卓系统中有,在“/system/fonts/”文件夹下,我的机器恰好就没有这个字体,所以我把字体放在项目assets文件夹,然后在使用时拷贝到sd卡中,若也没有此字体可以在此下载:https://download.csdn.net/download/qq_28708411/12594005 若没积分,可以在百度网盘中下载:链接:https://pan.baidu.com/s/1f9duJ4NabjaiSUvRDGOCoQ
提取码:h9rk
2.HTML文件中用到中文的,此“font-family:”属性要改为“my_font”,例如:是根据此设置的:3.使用到的jar包下载地址: https://download.csdn.net/download/qq_28708411/12593995 百度云地址:链接:https://pan.baidu.com/s/1wSnQyZaFp7nCDb0vUZNslg
提取码:roid
4.打印服务APK:链接:https://pan.baidu.com/s/1iYnkERaGQWUpuWbS0J6sdQ
提取码:ht1e
最后
以上就是俊秀柚子为你收集整理的android原生打印PDF,HTML;HTML转换为PDF的全部内容,希望文章能够帮你解决android原生打印PDF,HTML;HTML转换为PDF所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复