Android使用itextpdf操作PDF文档
package com.kl.common_base.utils;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.UiThread;
import android.util.Log;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
import com.kl.common_base.R;
import com.kl.common_base.base.BaseApplication;
import com.kl.common_base.bean.NoteEntity;
import com.kl.common_base.bean.RecordEntity;
import com.kl.common_base.constants.Constants;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Objects;
public class PdfUtil {
private File file;
private Font fontTitle1;
private Font fontTitle2;
private Font fontTitle3;
// private Font fontText;
// private Font fontText2;
// private Font fontText3;
private Document doc;
private PdfWriter writer;
private FileOutputStream fos;
// public static final String PDF_ROTE_PATH = BaseApplication.getApplication().getExternalFilesDir("pdf").getAbsolutePath();
// public final String MS = "ms";
// public final String BPM = "bpm";
// public final String MS_2 = "ms²";
// private int minValue = 0;
// private int cellHeight = 25;
/**
* 创建和分享pdf
* 要在子线程执行
*/
public PdfUtil buildPdf(RecordEntity recordEntity, String hospitalNameStr, String numberStr, String resultStr) throws Exception {
long createTime = DateUtils.formatTimeToLong(recordEntity.getCreateTime(), Constants.TIME_FORMAT_UTC);
file = FileUtils.createPdfFile(createTime);
//1创建document实例,无参默认A4纸
doc = new Document(PageSize.A4, 5f, 5f, 25f, 15f);//创建一个document对象
fos = new FileOutputStream(file); //pdf_address为Pdf文件保存到sd卡的路径
//2创建Writer实例,pdf直接使用的DocWriter的实现类PdfWriter
writer = PdfWriter.getInstance(doc, fos);
writer.setPageEvent(new HeaderAndFooter());
doc.open();
// doc.setPageCount(1);
fontTitle1 = setChineseFont(26, Font.BOLD, Constants.FILE_PATH_FONT);
// fontTitle1.setColor(76, 199, 191);
fontTitle2 = setChineseFont(16, Font.BOLD, Constants.FILE_PATH_FONT);
// fontTitle2.setColor(76, 199, 191);
fontTitle3 = setChineseFont(12, Font.NORMAL, Constants.FILE_PATH_FONT);
fontTitle3.setColor(76, 199, 191);
// fontText = setChineseFont(12, Font.NORMAL, fontPath);
// fontText2 = setChineseFont(8, Font.NORMAL, fontPath);
// fontText3 = setChineseFont2(12, Font.NORMAL, fontPath);
Paragraph paragraph = new Paragraph(hospitalNameStr, fontTitle1);
paragraph.setLeading(paragraph.getLeading() - 10);//行距
paragraph.setAlignment(Element.TITLE);//设置文字水平居中
paragraph.setSpacingBefore(26);
doc.add(paragraph);
paragraph = new Paragraph("心音图报告", fontTitle2);
paragraph.setLeading(paragraph.getLeading() - 10);
paragraph.setAlignment(Element.TITLE);//设置文字水平居中
paragraph.setSpacingBefore(20);
doc.add(paragraph);
doc.add(Chunk.NEWLINE);//换行
doc.add(Chunk.NEWLINE);
NoteEntity mNoteEntity = JsonUtils.formJsonString(recordEntity.getNote(), NoteEntity.class);
paragraph = new Paragraph("姓名:" + mNoteEntity.getName(), fontTitle3);
paragraph.setLeading(paragraph.getLeading() - 10);//行距
paragraph.setAlignment(Element.ALIGN_LEFT);//设置文字水平居中
paragraph.setSpacingBefore(14);
paragraph.setIndentationLeft(14);
doc.add(paragraph);
paragraph = new Paragraph("年龄:" + mNoteEntity.getAge(), fontTitle3);
paragraph.setLeading(paragraph.getLeading() - 10);
paragraph.setAlignment(Element.ALIGN_LEFT);//设置文字水平居中
paragraph.setSpacingBefore(14);
paragraph.setIndentationLeft(14);
doc.add(paragraph);
Resources resource = BaseApplication.getApplication().getResources();
String gender = mNoteEntity.getGender() == 1 ? resource.getString(R.string.gender_female) : resource.getString(R.string.gender_male);
paragraph = new Paragraph("性别:" + gender, fontTitle3);
paragraph.setLeading(paragraph.getLeading() - 10);
paragraph.setAlignment(Element.ALIGN_LEFT);//设置文字水平居中
paragraph.setSpacingBefore(14);
paragraph.setIndentationLeft(14);
doc.add(paragraph);
paragraph = new Paragraph("门诊/住院号:" + numberStr, fontTitle3);
paragraph.setLeading(paragraph.getLeading() - 10);
paragraph.setAlignment(Element.ALIGN_LEFT);//设置文字水平居中
paragraph.setSpacingBefore(14);
paragraph.setIndentationLeft(14);
doc.add(paragraph);
paragraph = new Paragraph("备注信息:" + mNoteEntity.getComment(), fontTitle3);
paragraph.setLeading(paragraph.getLeading() - 10);
paragraph.setAlignment(Element.ALIGN_LEFT);//设置文字水平居中
paragraph.setSpacingBefore(14);
paragraph.setIndentationLeft(14);
doc.add(paragraph);
// 图片
// Image image2 = Image.getInstance(new URL("http://c.hiphotos.baidu.com/image/pic/item/9c16fdfaaf51f3de1e296fa390eef01f3b29795a.jpg"));
// //将图片2添加到pdf文件中
// doc.add(image2);
doc.add(Chunk.NEWLINE);
String fileDir = Constants.FILE_PATH_DATA + "/" + DateUtils.getFormatDate(createTime, Constants.TIME_FORMAT_FILE) + "/wave_view/";
Log.d("caowj", "截图目录:" + fileDir);
File file = new File(fileDir);
if (file.exists() && file.isDirectory()) {
// doc.newPage();
float scale = (SizeUtils.getScreenWidth() * 1.0f - SizeUtils.dp2px(20)) / SizeUtils.dp2px(175f);
float imgWidth = PageSize.A4.getWidth() - 10f;
float imgHeight = imgWidth / scale;
File flist[] = file.listFiles();
for (File f : flist) {
Log.d("caowj", "截图=" + f.getName());
Image image = Image.getInstance(f.getAbsolutePath());
// image.scaleAbsolute(120, 45);
// image.scaleAbsoluteHeight(100f); // 将图像缩放到绝对高度。
// image.scaleAbsoluteWidth(pageWidth); // 将图像缩放到绝对宽度。
// image.scalePercent(30f);
image.scaleAbsolute(imgWidth, imgHeight);
image.setAlignment(Element.ALIGN_LEFT);
image.setIndentationLeft(2);
doc.add(image);
doc.add(Chunk.NEWLINE);
}
}
doc.add(Chunk.NEWLINE);
paragraph = new Paragraph("听诊总时长:" + DateUtils.getFormatAudioMinSec(recordEntity.getTotalTime()), fontTitle3);
paragraph.setLeading(paragraph.getLeading() - 10);
paragraph.setAlignment(Element.ALIGN_LEFT);//设置文字水平居中
paragraph.setSpacingBefore(14);
paragraph.setIndentationLeft(14);
doc.add(paragraph);
paragraph = new Paragraph("结论:" + resultStr, fontTitle3);
// paragraph.setLeading(paragraph.getLeading() - 10);
// paragraph.setLeading(1.5f);
paragraph.setMultipliedLeading(1.2f);
paragraph.setAlignment(Element.ALIGN_LEFT);//设置文字水平居中
paragraph.setSpacingBefore(14);
paragraph.setIndentationLeft(14);
doc.add(paragraph);
doc.add(Chunk.NEWLINE);//换行
doc.add(Chunk.NEWLINE);//换行
doc.add(Chunk.NEWLINE);//换行
doc.add(new Paragraph("\n"));
doc.add(new Paragraph("\n"));
doc.add(new Paragraph("\n"));
doc.add(new Paragraph("\n"));
Image image = Image.getInstance(getSignImage());
image.scaleAbsolute(50, 50); // 设置图像的大小
paragraph = new Paragraph("医生签字:", fontTitle3);
Log.d("caowj", "行间距:" + paragraph.getLeading());
paragraph.add(new Chunk(image, 10, -20)); // 将图像添加到短语中
paragraph.setLeading(paragraph.getLeading() - 10);
paragraph.setAlignment(Element.ALIGN_CENTER);//设置文字水平居中
// paragraph2.setSpacingBefore(20);// 前间距
// paragraph2.setSpacingAfter(80);// 后间距
paragraph.setIndentationLeft(200f);// 右缩进
doc.add(paragraph);
doc.add(Chunk.NEWLINE);//换行
doc.add(Chunk.NEWLINE);//换行
doc.add(Chunk.NEWLINE);//换行
// //设置属性
// //标题
// doc.addTitle("this is a title");
// //作者
// doc.addAuthor("H__D");
// //主题
// doc.addSubject("this is subject");
// //关键字
// doc.addKeywords("Keywords");
// //创建时间
// doc.addCreationDate();
// //应用程序
// doc.addCreator("hd.com");
// //表格
// float[] widths = {144, 113, 191};
// PdfPTable table = new PdfPTable(widths);
// table.setTotalWidth(458);
// table.setHorizontalAlignment(Element.ALIGN_LEFT);
// Object[][] datas = {{"区域", "总销售额(万元)", "总利润(万元)简单的表格"}, {"江苏省", 9045, 2256}, {"广东省", 3000, 690}};
//
// for (int i = 0; i < datas.length; i++) {
// for (int j = 0; j < datas[i].length; j++) {
// PdfPCell pdfCell = new PdfPCell(); //表格的单元格
// Paragraph paragraph3 = new Paragraph("" + datas[i][j], fontTitle1);
// pdfCell.setPhrase(paragraph3);
// table.addCell(pdfCell);
// }
// }
//
// doc.add(table); //pdf文档中加入table
return this;
}
private byte[] getSignImage() {
Resources resource = BaseApplication.getApplication().getResources();
Bitmap bitmap = BitmapFactory.decodeResource(resource, R.drawable.icon_collected);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
byte[] bytes = outputStream.toByteArray();
// outputStream.close();
return bytes;
}
//
// public PdfUtil createUserInfo(RecordBean patient, String hotName, boolean isNewPage, String pdfLogo) throws Exception {
// if (isNewPage) {
// doc.newPage();
Image image = Image.getInstance(pdfLogo);
image.scaleAbsolute(120, 45);
image.setAlignment(Element.ALIGN_LEFT);
image.setIndentationLeft(20);
doc.add(image);
doc.add(Chunk.NEWLINE);
// Paragraph paragraph = new Paragraph("糖尿病心脏自主神经病变分析报告", fontTitle1);
// paragraph.setLeading(paragraph.getLeading() - 10);
// paragraph.setAlignment(Element.TITLE);//设置文字水平居中
// paragraph.setSpacingBefore(20);
// doc.add(paragraph);
//
// }
// doc.add(Chunk.NEWLINE);//换行
// PdfPTable table = new PdfPTable(3);
// String name = patient.getPatientName();
// String gender = patient.getGender() == 0 ? "女" : "男";
// String age = patient.getAge() + "岁";
// String department = patient.getDepartment();
// String admissionNo = patient.getAdmissionNo();
// String bedNo = patient.getBedNo();
// String[] type = {
// "医院:" + hotName,
// "姓名:" + name,
// "性别:" + gender,
// "年龄:" + age,
// "科室:" + department,
// "住院号:" + admissionNo,
// "床号:" + bedNo
// };
// // 设置表格默认为无边框
// table.getDefaultCell().setBorder(0);
// for (int i = 0; i < type.length; i++) {
// Paragraph userInfo = new Paragraph(type[i], fontText);
// PdfPCell cell = new PdfPCell(userInfo);
// if (i == 0) {
// cell.setColspan(3);
// }
// cell.setBorder(Rectangle.NO_BORDER);
// cell.setHorizontalAlignment(Element.ALIGN_LEFT);
// cell.setFixedHeight(cellHeight);
// // 设置垂直居中
// cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.A);
// table.addCell(cell);
// }
// table.setWidthPercentage(85);
if(!isNewPage)
table.setSpacingBefore(20);
// doc.add(table);
// return this;
// }
//
//
// /**
// * 添加神经反射表格
// */
// public PdfUtil createReflectTable(double[] result0, double[] result1, double[] result2, float hrDiff) throws DocumentException {
// doc.add(Chunk.NEWLINE);//换行
// Paragraph paragraph = new Paragraph("心脏自主神经反射实验", fontTitle2);
// paragraph.setLeading(paragraph.getLeading() - 15);
// paragraph.setSpacingBefore(20);