用java代码实现pdf打印

以下是代码模板以及注释

说明:

  1. 代码中的的查询可以替换成自己想要的测试内容此处不再修改
  2. 代码默认生成两个pdf一个带水印一个不带(此处可以定义为绝对路径)
  3. 文种sql查询所需的jdbc代码此处不再给出自己去写
  4. 关于jar包的的问题,拿出代码修改过后根据报错自行添加jar包此处不再给出

5.我此处写的代码包含service,如果自己开发工具测试,请去掉这段

可能会出现的报错:

  1. 导入的类报错:可能没有jar包或这没有该类没有类文件的直接删掉
  2. 路径不存在:我的电脑路径在你的电脑中不一定存在,所以根据报错位置修改路径

 

import java.awt.FontMetrics;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.MalformedURLException;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.text.DecimalFormat;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Calendar;

 

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.swing.JLabel;

 

import org.apache.struts2.ServletActionContext;

 

import wingsoft.custom.Global;

import wingsoft.tool.db.ConnectionPool;

import wingsoft.tool.db.ConnectionPoolManager;

 

import com.itextpdf.text.Document;

import com.itextpdf.text.DocumentException;

import com.itextpdf.text.Element;

import com.itextpdf.text.ExceptionConverter;

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.Rectangle;

import com.itextpdf.text.pdf.BaseFont;

import com.itextpdf.text.pdf.ColumnText;

import com.itextpdf.text.pdf.PdfContentByte;

import com.itextpdf.text.pdf.PdfGState;

import com.itextpdf.text.pdf.PdfPCell;

import com.itextpdf.text.pdf.PdfPTable;

import com.itextpdf.text.pdf.PdfPageEventHelper;

import com.itextpdf.text.pdf.PdfReader;

import com.itextpdf.text.pdf.PdfStamper;

import com.itextpdf.text.pdf.PdfTemplate;

import com.itextpdf.text.pdf.PdfWriter;

 

/*

* 作者:lesen

* 注释:此文件为test下的文件复制而来出错时可以对照其文件

*

* */

public class CxPdfPrint {

private static String FONT = “./style/simsun.ttc,1”;

private static String DEST = “./uploadfiles/HelloWorld.pdf”;

 

private static final long serialVersionUID = 1L;

private InputStream responseText;         //AJAX 请求响应文本流

FileInputStream inputStream;       //输出到客户端的文件流

 

public void setResponseText(InputStream responseText) {

this.responseText = responseText;

}

public InputStream getResponseText() {

return responseText;

}

public FileInputStream getInputStream() {

return inputStream;

}

public void setInputStream(FileInputStream inputStream) {

this.inputStream = inputStream;

}

 

public static String getFONT() {

return FONT;

}

public static void setFONT(String fONT) {

FONT = fONT;

}

public static String getDEST() {

return DEST;

}

public static void setDEST(String dEST) {

DEST = dEST;

}

/**

* 格式化金额

*

* @param dNumber

* @param fmtStr

*            “###,###,###,###,###,##0.00”

* @return

*/

public String formatDecimal(double dNumber, String fmtStr) {

return new DecimalFormat(fmtStr).format(dNumber);

}

/**

* 下載pdf

* @return

*/

public void getFFcjData() {

HttpServletRequest request = ServletActionContext.getRequest();

HttpServletResponse response = ServletActionContext.getResponse();

ConnectionPool pool = ConnectionPoolManager.getPool(“CMServer”);

Connection connection = null;

PreparedStatement ps = null;

ResultSet rs = null;

 

String contextPath = request.getSession().getServletContext().getRealPath(“/”);

 

Calendar cal = Calendar.getInstance();

long thismillsecond = cal.getTimeInMillis();

String filename = “ff”+thismillsecond+”.pdf”;

 

java.util.Date date = cal.getTime();

String outFilename = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”).format(date);

 

setDEST(contextPath+”/uploadfiles/”+filename);

setFONT(contextPath+”/style/simsun.ttc,1″);

 

String cjtype = “”;

String[] titleArr = new String[2];

ArrayList<Font> titleFontArr = new ArrayList<Font>();

 

doctitle2 += ” 查询时间:”+outFilename+””;

 

 

try {

connection = pool.getConnection();

 

// 创建一个文档(默认大小A4,边距36, 36, 36, 36)

Document document = new Document();

// 创建writer,通过writer将文档写入磁盘

PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(DEST));

Font keyfont = new Font(BaseFont.createFont(FONT, BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED), 9, Font.BOLD);

Font titlefont = new Font(BaseFont.createFont(FONT, BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED), 13, Font.BOLD);

Font textfont = FontFactory.getFont(FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED, 9, Font.NORMAL, null);

Font font1 = FontFactory.getFont(“黑体”, BaseFont.WINANSI, 12);

BaseFont footFont = BaseFont.createFont(FONT, BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);

// 增加页眉页脚

writer.setPageEvent(new Footer(footFont));

// 设置文档大小

document.setPageSize(PageSize.A4.rotate());

// 设置边距,单位都是像素,换算大约1厘米=28.33像素

document.setMargins(10, 10, 50, 30);

// 打开文档,只有打开后才能往里面加东西

document.open();

// 设置作者

document.addAuthor(“lesen”);

// 设置创建者

document.addCreator(“lesen);

// 设置主题

document.addSubject(“lesen “);

 

//创建表头以及对应字段

String col[]={“部门代码”,”部门名称”,”所在地”};

//字段必须与查询sql查询出来的的字段一致

String zd []={“deptno”,”dname”,”loc”};

 

// 创建表格,8列的表格

PdfPTable table = new PdfPTable(3);

int[] tableTdWidth = {50,50,50};

table.setWidths(tableTdWidth);

table.setTotalWidth(PageSize.A4.rotate().getWidth()- 20);

table.setLockedWidth(true);

 

// 添加表头

// 添加表头,循环加载

 

for(int i=0;i<col.length;i++)

{//此处定义模板

table.addCell(createCell(col[i],keyfont,Element.ALIGN_CENTER,1,true));

}

 

String sql = “select deptno,dname,loc”;

“;

 

 

 

 

 

System.out.println(“查询sql:”+sql);

ps = connection.prepareStatement(sql);

rs = ps.executeQuery();

System.out.println(“此处已执行”);

Font fontType=null;

int ali=0;

while (rs.next())

{

 

//循环加载字段

for(int i=0;i<zd.length;i++)

{

table.addCell(createCell(Global.nTrim(rs.getString(zd[i])),fontType,ali,1,true));

}

 

}

titleArr[0] = “文件头_”+cjtype;

titleFontArr.add(titlefont);

titleArr[1] = doctitle2;

titleFontArr.add(keyfont);

Header headerTable = new Header(table,titleArr);

headerTable.setTableHeader(writer,titleFontArr);

//         Footer footerTable = new Footer(table,footFont);

//         footerTable.setTableFooter(writer, keyfont,”打印时间  “+outFilename);

//

document.add(table);

// 关闭文档,才能输出

document.close();

writer.close();

 

System.out.println(“文件创建成功——————————pdf-finished”);

addPdfWatermark(contextPath,”ff”+thismillsecond+”-2.pdf”);

 

InputStream inStream = new FileInputStream(contextPath+”/uploadfiles/ff”+thismillsecond+”-2.pdf”);// 文件的存放路径

 

// 设置输出的格式

response.reset();

response.setContentType(“application/pdf”);

response.addHeader(“Content-Disposition”, “attachment; filename=\””+outFilename+”.pdf\””);

// 循环取出流中的数据

byte[] b = new byte[100];

int len;

try {

while ((len = inStream.read(b)) > 0)

response.getOutputStream().write(b, 0, len);

inStream.close();

} catch (IOException e) {

e.printStackTrace();

}

System.out.println(“文件输出成功——————————pdf-out-finished”);

//删除临时pdf

File file = new File(contextPath+”/uploadfiles/ff”+thismillsecond+”.pdf”);

if(file.exists()){

file.delete();

System.out.println(“删除临时文件1成功——————————pdf-delete”);

}

file = new File(contextPath+”/uploadfiles/ff”+thismillsecond+”-2.pdf”);

if(file.exists()){

file.delete();

System.out.println(“删除临时文件-2成功——————————pdf-delete2”);

}

}

catch (Exception ex){

ex.printStackTrace();

System.out.println(“系统异常”);

}

finally {

if (rs!= null){

try {

rs.close();

} catch (SQLException e1) {

e1.printStackTrace();

}

}

 

try

{

if (ps != null) ps.close();

}

catch (SQLException e) {

e.printStackTrace();

}

pool.returnConnection(connection);

}

}

 

/**

* 为表格添加一个内容

* @param value  值

* @param font  字体

* @param align  对齐方式

* @param colspan 占多少列

* @param boderFlag 是否有有边框

* @return  添加的文本框

*/

public PdfPCell createCell(String value, Font font, int align, int colspan,boolean boderFlag){

PdfPCell cell = new PdfPCell();

cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

cell.setHorizontalAlignment(align);

cell.setColspan(colspan);

cell.setPhrase(new Phrase(value, font));

cell.setPadding(3.0f);

if (!boderFlag)

{

cell.setBorder(0);

cell.setPaddingTop(15.0f);

cell.setPaddingBottom(8.0f);

}

return cell;

}

 

/**

*

* @throws IOException

* @throws DocumentException

*/

public void addPdfWatermark(String contextpath,String filename) throws IOException, DocumentException{

PdfReader reader = new PdfReader(DEST);

PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(contextpath+”/uploadfiles/”+filename));

Image img = Image.getInstance(contextpath+”/img/cx_pdfwm.png”);

 

PdfContentByte contentByte = null;

int n = reader.getNumberOfPages();

//2. 设置透明度

PdfGState gs = new PdfGState();

gs.setFillOpacity(0.4f);

gs.setStrokeOpacity(0.4f);

 

//设置平铺参数

int interval = -5;

int textH = 0;

int textW = 0;

JLabel label = new JLabel();

FontMetrics metrics;

//此账单供项目办理结题时使用

label.setText(“此账单供项目办理结题时使用”);

//        label.setText(waterMarkName);

metrics = label.getFontMetrics(label.getFont());

textH = metrics.getHeight();

textW = metrics.stringWidth(label.getText());

Rectangle pageRect = null;

 

 

 

Rectangle rectangle = null;

//4.在pdf每页右上角添加条码

for (int i = 1; i <= n; i++){

pageRect =reader.getPageSizeWithRotation(i);

contentByte = stamp.getUnderContent(i);     // getOverContent 水印会把正文盖住    getUnderContent 水印会被正文的图片盖住

contentByte.setGState(gs);

//            contentByte.beginText();

//            contentByte.saveState();

//            under.setFontAndSize(base, 20);

rectangle = reader.getPageSize(i);

float width = rectangle.getWidth();

float height = rectangle.getHeight();

img.setAlignment(1);//居中显示

img.setAbsolutePosition(0, 0);

img.setRotation(-20);//同一片旋转幅度

img.setRotationDegrees(-45);//图片旋转角度

img.scalePercent(150);//图片大小的比例,百分比

contentByte.addImage(img);

 

//            for (int height1 = interval + textH; height1 < pageRect.getHeight();

//                    height1 = height1 + textH*3) {

//                for (int width1 = interval + textW; width1 < pageRect.getWidth() + textW;

//                        width1 = width1 + textW*2) {

//                contentByte.addImage(img);

////            under.showTextAligned(Element.ALIGN_LEFT

////                    , waterMarkName, width – textW,

////                    height1 – textH, 30);

//                }

//            }

// 添加水印文字

//            under.endText();

}

 

 

reader.close();

stamp.close();

}

 

//页眉事件

@SuppressWarnings(“unused”)

private static class Header extends PdfPageEventHelper {

public static PdfPTable header;

public static String[] headTextArr;

 

public Header(PdfPTable header,String[] headTextArr) {

Header.header = header;

Header.headTextArr = headTextArr;

}

 

@Override

public void onEndPage(PdfWriter writer, Document document) {

float doccenterIdx = PageSize.A4.getWidth()/2-headTextArr[0].getBytes().length/2;//X轴中间位置

//把页眉表格定位

header.writeSelectedRows(0, -1, 0,PageSize.A4.rotate().getHeight()-10 , writer.getDirectContent());

}

 

/**

* 设置页眉

* @param writer

* @param req

* @throws MalformedURLException

* @throws IOException

* @throws DocumentException

*/

public void setTableHeader(PdfWriter writer) throws MalformedURLException, IOException, DocumentException {

String imageAddress = “E://TESTPDF/”;

PdfPTable table = new PdfPTable(1);

//A4 横向宽度

table.setTotalWidth(PageSize.A4.rotate().getWidth());

PdfPCell cell = new PdfPCell();

cell.setBorder(0);

Image image01;

image01 = Image.getInstance(imageAddress + “testhead.png”); //图片自己传

//image01.scaleAbsolute(355f, 10f);

image01.setWidthPercentage(80);

cell.setPaddingLeft(30f);

cell.setPaddingTop(-20f);

cell.addElement(image01);

table.addCell(cell);

Header event = new Header(table,headTextArr);

writer.setPageEvent(event);

}

 

public void setTableHeader(PdfWriter writer,ArrayList<Font> titleFontArr) throws MalformedURLException, IOException, DocumentException {

PdfPTable table = new PdfPTable(1);

//A4 横向宽度

table.setTotalWidth(PageSize.A4.rotate().getWidth()- 20);

PdfPCell cell = new PdfPCell();

cell.setBorder(0);

cell.setPaddingLeft(10f);

cell.setPaddingTop(0f);

cell.setUseAscender(true);

cell.setHorizontalAlignment(Element.ALIGN_CENTER);

cell.setPhrase(new Phrase(headTextArr[0], titleFontArr.get(0)));

table.addCell(cell);

 

cell = new PdfPCell();

cell.setBorder(0);

cell.setPaddingLeft(10f);

cell.setPaddingTop(10f);

cell.setUseAscender(true);

cell.setFixedHeight(25);

cell.setHorizontalAlignment(Element.ALIGN_CENTER);

cell.setPhrase(new Phrase(headTextArr[1], titleFontArr.get(1)));

table.setHorizontalAlignment(Element.ALIGN_CENTER);

table.addCell(cell);

 

Header event = new Header(table,headTextArr);

writer.setPageEvent(event);

}

}

 

//页脚事件

@SuppressWarnings(“unused”)

private static class Footer extends PdfPageEventHelper {

public static PdfPTable footer;

public PdfTemplate tpl;

public BaseFont bf;

 

@SuppressWarnings(“static-access”)

public Footer(BaseFont  font) {

//        Footer.footer = table;

this.bf = font;

}

 

public void onOpenDocument(PdfWriter writer, Document document) {

try {

tpl = writer.getDirectContent().createTemplate(200, 30);

}

catch(Exception e) {

throw new ExceptionConverter(e);

}

}

 

@Override

public void onEndPage(PdfWriter writer, Document document) {

//把页脚表格定位

//            footer.writeSelectedRows(0, -1, PageSize.A4.rotate().getWidth()-200, 30, writer.getDirectContent());

//在每页结束的时候把“第x页”信息写道模版指定位置

PdfContentByte cb = writer.getDirectContent();

cb.saveState();

String text = “第” + writer.getPageNumber() + “页,共”;

cb.beginText();

cb.setFontAndSize(bf, 10);

cb.setTextMatrix(PageSize.A4.rotate().getWidth()-100, 20);//定位“第x页,共” 在具体的页面调试时候需要更改这xy的坐标

cb.showText(text);

cb.endText();

cb.addTemplate(tpl, PageSize.A4.rotate().getWidth()-50, 20);//定位“y页” 在具体的页面调试时候需要更改这xy的坐标

 

//            cb.saveState();

cb.stroke();

cb.restoreState();

cb.closePath();//

}

 

/**

* 页脚是图片

* @param writer

* @throws MalformedURLException

* @throws IOException

* @throws DocumentException

*/

public void setTableFooter(PdfWriter writer) throws MalformedURLException, IOException, DocumentException {

String imageAddress = “E://TESTPDF/”;

PdfPTable table = new PdfPTable(1);

table.setTotalWidth(523);

PdfPCell cell = new PdfPCell();

cell.setBorder(1);

Image image01;

image01 = Image.getInstance(imageAddress + “testfooter.png”); //图片自己传

image01.scaleAbsoluteWidth(523);

image01.scaleAbsoluteHeight(30f);

image01.setWidthPercentage(100);

cell.addElement(image01);

table.addCell(cell);

Footer event = new Footer(bf);

writer.setPageEvent(event);

}

 

/**

* 页脚是文字

* @param writer

* @param songti09

*/

public void setTableFooter(PdfWriter writer, Font songti09,String footText) {

PdfPTable table = new PdfPTable(1);

table.setTotalWidth(500f);

PdfPCell cell = new PdfPCell();

cell.setBorder(0);

Paragraph p = new Paragraph(“第” + writer.getPageNumber() + “页/”, songti09);

//cell.setPaddingLeft(10f);

//cell.setPaddingTop(-2f);

//            cell.setPaddingBottom(2f);

//            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);

//            cell.addElement(p);

//            table.addCell(cell);

Footer event = new Footer(bf);

writer.setPageEvent(event);

}

 

// 全部完成后,将总页数的pdf模版写到指定位置

public void onCloseDocument(PdfWriter writer,Document document) {

tpl.beginText();

tpl.setFontAndSize(bf, 10);

tpl.showText(”  “+Integer.toString(writer.getPageNumber() – 1)+”页”);

tpl.endText();

tpl.closePath();//sanityCheck();

}

}

}

评论

  1. 4207
    Chrome 63.0.3239.132
    7 年前
    2019-5-30 15:16:44

    谢谢博主分享。这里有一个不错的Spire.Pdf打印控件,代码量少得多。
    import com.spire.pdf.*;
    import java.awt.print.*;

    public class Print {
    public static void main(String[] args) {
    //创建PDF实例并加载源文件
    PdfDocument pdf = new PdfDocument();
    pdf.loadFromFile(“Sample.pdf”);

    PrinterJob loPrinterJob = PrinterJob.getPrinterJob();
    PageFormat loPageFormat = loPrinterJob.defaultPage();
    Paper loPaper = loPageFormat.getPaper();

    //移除默认的打印边距
    loPaper.setImageableArea(0,0,loPageFormat.getWidth(),loPageFormat.getHeight());

    //设置打印的份数
    loPrinterJob.setCopies(2);

    loPageFormat.setPaper(loPaper);
    loPrinterJob.setPrintable(pdf,loPageFormat);
    try {
    loPrinterJob.print();
    } catch (PrinterException e) {
    e.printStackTrace();
    }
    }
    }

    • lesen
      博主
      4207
      MSIE 7.0
      7 年前
      2019-5-31 16:15:14

      谢谢

本文评论已关闭
上一篇
下一篇