① 有哪位大俠做過itext的pdf開發,設置頁眉和頁腳的時候的是圖片,我用的版本是5.3.4的。現在弄不上圖片,急
以Wps 2019版本為例:
關於PDF如何添加頁眉頁腳的操作方法,我們推薦您可考慮使用WPS2019來完成,操作步驟如下:
1、打開「PDF文檔」;
2、點擊「插入-頁碼」/「插入-頁眉頁腳」(提示該功能需開通WPS會員使用);
3、可根據需求設置頁面或頁眉頁腳的參數來進行插入。
② 如何運用Java組件itext生成pdf
Controller層(param為數據)
byte[]bytes=PdfUtils.createPdf(param);
ByteArrayInputStreaminStream=newByteArrayInputStream(bytes);
//設置輸出的格式
response.setContentType("bin");
response.setHeader("content-disposition","attachment;filename="+URLEncoder.encode(itemName+"(評審意見).pdf","UTF-8"));
//循環取出流中的數據
byte[]b=newbyte[2048];
intlen;
while((len=inStream.read(b))>0)
response.getOutputStream().write(b,0,len);
inStream.close();
Service層(param為數據)
public static byte[] createPdf(Map<String,Object> param) {
byte[] result= null;
ByteArrayOutputStream baos = null;
//支流程評審信息匯總
List<CmplncBranchRvwInfoDTO> branchRvwInfos = (List<CmplncBranchRvwInfoDTO>) param.get("branchRvwInfos");
//主流程評審信息匯總
List<CmplncMainRvwInfoDTO> mainRvwInfos = (List<CmplncMainRvwInfoDTO>) param.get("mainRvwInfos");
//主評審信息
CmplncRvwFormDTO rvwFormDTO = (CmplncRvwFormDTO) param.get("rvwFormDTO");
//附件列表
List<FileInfoDTO> fileList = (List<FileInfoDTO>) param.get("fileList");
//專業公司
String legalEntityDeptDesc = (String) param.get("legalEntityDeptDesc");
String legalEntitySonDeptDesc = (String) param.get("legalEntitySonDeptDesc");
//設置頁邊距
Document doc = new Document(PageSize.A4, 20, 20, 60, 20);
try {
baos = new ByteArrayOutputStream();//構建位元組輸出流
PdfWriter writer = PdfWriter.getInstance(doc,baos);
//頁眉頁腳字體
BaseFont bf = null;
BaseFont bFont = null;
try {
bFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
} catch (Exception e) {
e.printStackTrace();
}
Font footerFont = new Font(bFont, 10, Font.NORMAL);
Font title = new Font(bf,15,Font.BOLD);
Font content = new Font(bf,9,Font.NORMAL);
Font chinese = new Font(bf, 10, Font.BOLD);
/**
* HeaderFooter的第2個參數為非false時代表列印頁碼
* 頁眉頁腳中也可以加入圖片,並非只能是文字
*/
HeaderFooter header=new HeaderFooter(new Phrase("法律合規評審系統",title),false);
//設置是否有邊框等
header.setBorder(Rectangle.NO_BORDER);
header.setAlignment(1);
doc.setHeader(header);
HeaderFooter footer=new HeaderFooter(new Phrase("-",footerFont),new Phrase("-",footerFont));
/**
* 0左 1中 2右
*/
footer.setAlignment(1);
footer.setBorder(Rectangle.NO_BORDER);
doc.setFooter(footer);
doc.open();
//doc.add(new Paragraph("評審意見:",chinese));
//7列
PdfPTable table = new PdfPTable(7);
PdfPCell cell;
table.addCell(new Paragraph("評審項目編號",chinese));
table.addCell(new Paragraph(rvwFormDTO.getRvwItemCode(),content));
cell = new PdfPCell(new Paragraph("評審項目類型",chinese));
cell.setColspan(2);
table.addCell(cell);
String rvwItemParentType = (String) param.get("rvwItemParentType");
String rvwItemType = (String) param.get("rvwItemType");
String rvwItemTwoType = (String) param.get("rvwItemTwoType");
cell = new PdfPCell(new Paragraph(rvwItemParentType+"/"+rvwItemType+"/"+rvwItemTwoType,content));
cell.setColspan(3);
table.addCell(cell);
table.addCell(new Paragraph("申請人姓名",chinese));
table.addCell(new Paragraph(rvwFormDTO.getApplicantName(),content));
cell = new PdfPCell(new Paragraph("申請人所在部門",chinese));
cell.setColspan(2);
table.addCell(cell);
cell = new PdfPCell(new Paragraph(rvwFormDTO.getAplcntDeptName(),content));
cell.setColspan(3);
table.addCell(cell);
table.addCell(new Paragraph("錄入人姓名",chinese));
table.addCell(new Paragraph(rvwFormDTO.getRecordName(),content));
cell = new PdfPCell(new Paragraph("項目涉及金額",chinese));
cell.setColspan(2);
table.addCell(cell);
table.addCell(new Paragraph(String.valueOf(rvwFormDTO.getInvolveAmount()==null?0:rvwFormDTO.getInvolveAmount()),content));
table.addCell(new Paragraph("幣種",chinese));
String involveAmountType = (String) param.get("involveAmountType");
table.addCell(new Paragraph(involveAmountType,content));
table.addCell(new Paragraph("專業公司",chinese));
cell = new PdfPCell(new Paragraph(legalEntityDeptDesc+"->"+legalEntitySonDeptDesc,content));
cell.setColspan(6);
table.addCell(cell);
table.addCell(new Paragraph("項目名稱",chinese));
cell = new PdfPCell(new Paragraph(rvwFormDTO.getItemName(),content));
cell.setColspan(6);
table.addCell(cell);
table.addCell(new Paragraph("項目概述",chinese));
cell = new PdfPCell(new Paragraph(rvwFormDTO.getItemOverview(),content));
cell.setColspan(6);
table.addCell(cell);
table.addCell(new Paragraph("評審需求",chinese));
cell = new PdfPCell(new Paragraph(rvwFormDTO.getRvwDemand(),content));
cell.setColspan(6);
table.addCell(cell);
table.addCell(new Paragraph("申請人自我評估",chinese));
cell = new PdfPCell(new Paragraph(rvwFormDTO.getApplicantSelfAssmnt(),content));
cell.setColspan(6);
table.addCell(cell);
/* table.addCell(new Paragraph("同步抄送",chinese));
cell = new PdfPCell(new Paragraph(rvwFormDTO.getSyncsenderNames(),content));
cell.setColspan(6);
table.addCell(cell);*/
int infoNum = 0;
if(fileList.size() > 0){
//附件信息
cell = new PdfPCell(new Paragraph("附件信息",chinese));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
cell.setRowspan(fileList.size()+1);
table.addCell(cell);
//序號
cell = new PdfPCell(new Paragraph("序號",chinese));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//附件名稱
cell = new PdfPCell(new Paragraph("附件名稱",chinese));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//上傳時間
cell = new PdfPCell(new Paragraph("上傳時間",chinese));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//上傳人
cell = new PdfPCell(new Paragraph("上傳人",chinese));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//附件類型
cell = new PdfPCell(new Paragraph("附件類型",chinese));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//法律合規評審
cell = new PdfPCell(new Paragraph("法律合規評審",chinese));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
for (FileInfoDTO file : fileList) {
infoNum++;
//序號
cell = new PdfPCell(new Paragraph(infoNum+"",content));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//附件名稱
cell = new PdfPCell(new Paragraph(file.getFileName(),content));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//上傳時間
cell = new PdfPCell(new Paragraph(file.getUploadTimeFormat(),content));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//上傳人
cell = new PdfPCell(new Paragraph(file.getUploadName(),content));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//附件類型
String fileType;
if("1".equals(file.getFileType())){
fileType = "合同文件";
}else if("99".equals(file.getFileType())){
fileType = "支持文檔";
}else{
fileType = "";
}
cell = new PdfPCell(new Paragraph(fileType,content));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//法律合規評審
String typeRvwStatus;
if("1".equals(file.getTypeRvwStatus())){
typeRvwStatus = "經審查附件無重大法律合規問題";
}else if("2".equals(file.getTypeRvwStatus())){
typeRvwStatus = "退回修改";
}else{
typeRvwStatus = "";
}
cell = new PdfPCell(new Paragraph(typeRvwStatus,content));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
}
}else{
//附件信息
cell = new PdfPCell(new Paragraph("附件信息",chinese));
table.addCell(cell);
cell = new PdfPCell(new Paragraph("沒有附件",content));
cell.setColspan(6);
table.addCell(cell);
}
cell = new PdfPCell(new Paragraph("評審意見",chinese));
cell.setRowspan(mainRvwInfos.size()+branchRvwInfos.size());
//居中
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
if(mainRvwInfos.size()>0){
cell = new PdfPCell(new Paragraph("主評審意見",chinese));
cell.setRowspan(mainRvwInfos.size());
//居中
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
infoNum = 0;
for (CmplncMainRvwInfoDTO dto : mainRvwInfos) {
infoNum++;
//序號
cell = new PdfPCell(new Paragraph(infoNum+"",content));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//評審意見
PdfPTable branchRvwInfosTable = new PdfPTable(1);
cell = new PdfPCell(new Paragraph(delHTMLTag(dto.getRvwOpinion()),content));
cell.disableBorderSide(2);
branchRvwInfosTable.addCell(cell);
//評審人和評審時間
cell = new PdfPCell(new Paragraph(dto.getRvwUmName()+"/"+getStringDate(dto.getRvwTime()),content));
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
cell.disableBorderSide(1);
cell.setPaddingTop(5);
branchRvwInfosTable.addCell(cell);
PdfPCell branchRvwInfosCell = new PdfPCell(branchRvwInfosTable);
branchRvwInfosCell.setColspan(4);
table.addCell(branchRvwInfosCell);
}
doc.add(table);
}
if(branchRvwInfos.size()>0){
cell = new PdfPCell(new Paragraph("支評審意見",chinese));
cell.setRowspan(branchRvwInfos.size());
//居中
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
infoNum = 0;
for (CmplncBranchRvwInfoDTO dto : branchRvwInfos) {
infoNum++;
//序號
cell = new PdfPCell(new Paragraph(infoNum+"",content));
cell.setUseAscender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell);
//評審意見
PdfPTable branchRvwInfosTable = new PdfPTable(1);
cell = new PdfPCell(new Paragraph(delHTMLTag(dto.getRvwOpinion()),content));
cell.disableBorderSide(2);
branchRvwInfosTable.addCell(cell);
//評審人和評審時間
cell = new PdfPCell(new Paragraph(dto.getRvwUmName()+"/"+getStringDate(dto.getRvwTime()),content));
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
cell.disableBorderSide(1);//隱藏上邊框
cell.setPaddingTop(5);
branchRvwInfosTable.addCell(cell);
PdfPCell branchRvwInfosCell = new PdfPCell(branchRvwInfosTable);
branchRvwInfosCell.setColspan(4);
table.addCell(branchRvwInfosCell);
}
doc.add(table);
}
if(doc != null){
doc.close();
}
result =baos.toByteArray();
} catch (DocumentException e) {
e.printStackTrace();
}finally{
if(baos != null){
try {
baos.close();
} catch (IOException e) {
log.error("PDF異常", e);
}
}
}
return result;
}
工具
/**
* 去掉HTML標簽
* @param htmlStr
* @return
*/
public static String delHTMLTag(String htmlStr){
if (htmlStr!=null){
String regEx_script="<script[^>]*?>[\s\S]*?<\/script>"; //定義script的正則表達式
String regEx_style="<style[^>]*?>[\s\S]*?<\/style>"; //定義style的正則表達式
String regEx_html="<[^>]+>"; //定義HTML標簽的正則表達式
Pattern p_script=Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);
Matcher m_script=p_script.matcher(htmlStr);
htmlStr=m_script.replaceAll(""); //過濾script標簽
Pattern p_style=Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE);
Matcher m_style=p_style.matcher(htmlStr);
htmlStr=m_style.replaceAll(""); //過濾style標簽
Pattern p_html=Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);
Matcher m_html=p_html.matcher(htmlStr);
htmlStr=m_html.replaceAll(""); //過濾html標簽
Pattern p_enter = Pattern.compile("\s*| | | ");
Matcher m_enter = p_enter.matcher(htmlStr);
htmlStr = m_enter.replaceAll("");
}
return htmlStr.trim().replaceAll(" ", ""); //返迴文本字元串
}
/**
* @return返回字元串格式 yyyy-MM-dd HH:mm:ss
*/
public static String getStringDate(Date date) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(date);
return dateString;
}
③ 我要用iText列印PDF文檔,但是頁眉頁腳不知道怎麼添加圖片,請各位大蝦指教
以WPS 2019版本為例:
關於PDF如何添加頁眉頁腳的操作方法,我們推薦您可考慮使用WPS2019來完成,操作步驟如下:
1、打開「PDF文檔」;
2、點擊「插入-頁碼」/「插入-頁眉頁腳」(提示該功能需開通WPS會員使用);
3、可根據需求設置頁面或頁眉頁腳的參數來進行插入。
④ java itext製作pdf 有一百行數據 自動生成了10頁 怎麼在這10頁上都加上背景圖片跪求
如果調整字體大小變成
⑤ java 如何給pdf文件加水印
Java生成PDF 加密 水印
1、iText簡介
iText是一個開放源碼的Java類庫,可以用來方便地生成PDF文件。大家通過訪問http://sourceforge.net/project/showfiles.php?group_id=15255&release_id=167948
下載最新版本的類庫,下載完成之後會得到一個.jar包,把這個包加入JDK的classpath即可使用。
如果生成的PDF文件中需要出現中文、日文、韓文字元,則還需要通過訪問http://itext.sourceforge.net/downloads/iTextAsian.jar
下載iTextAsian.jar包。
關於iText類庫的使用,http://www.lowagie.com/iText/tutorial/index.html
有比較詳細的教程。該教程從入門開始,比較系統地介紹了在PDF文件中放入文字、圖片、表格等的方法和技巧。
讀完這片教程,大致就可以做一些從簡單到復雜的PDF文件了。不過,試圖通過教程解決在生成PDF文件過程中遇到的所有困難無疑是一種奢望。所以,閱讀iText的api文檔顯得非常重要。讀者在下載類庫的同時,也可以下載類庫的文檔。
註:如果以上兩個下載鏈接無法下載而且通過網路也找不到這個jar包的同志可以留下郵箱地址,我會在兩個工作日之內發郵件過去。
以下部分我是我調試通過的源代碼,提供大家參考:
import java.awt.*;
import java.io.*;
import com.lowagie.text.*;
import com.lowagie.text.Font;
import
com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.*;
/**
* 最近的項目中使用Itext將txt文件轉換為PDF文件, 並且實現對文件的一些許可權控制。
現實對pdf文件加
*密,添加水印等。
*/
public class PDFConvertBL
{
//
txt原始文件的路徑
private static final String txtFilePath = "d:/11.txt";
// 生成的pdf文件路徑
private static final String pdfFilePath =
"d:/22.pdf";
// 添加水印圖片路徑
// private static final String
imageFilePath = "D:/33.jpg";
// 生成臨時文件前綴
private static final
String prefix = "tempFile";
// 所有者密碼
private static final String
OWNERPASSWORD = "12345678";
/**
* txt文件轉換為pdf文件
*
* @param txtFile
txt文件路徑
* @param pdfFile pdf文件路徑
* @param userPassWord
用戶密碼
* @param waterMarkName 水印內容
* @param permission
操作許可權
*/
public static void generatePDFWithTxt(String txtFile,
String pdfFile, String userPassWord, String
waterMarkName,
int permission)
{
try
{
// 生成臨時文件
File file =
File.createTempFile(prefix, ".pdf");
//
創建pdf文件到臨時文件
if (createPDFFile(txtFile, file))
{
// 增加水印和加密
waterMark(file.getPath(),
pdfFile, userPassWord, OWNERPASSWORD, waterMarkName, permission);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 創建PDF文檔
*
* @param txtFilePath
txt文件路徑(源文件)
* @param pdfFilePath pdf文件路徑(新文件)
*/
private
static boolean createPDFFile(String txtFilePath, File file)
{
// 設置紙張
Rectangle rect = new Rectangle(PageSize.A4);
//
設置頁碼
HeaderFooter footer = new HeaderFooter(new Phrase("頁碼:",
setChineseFont()), true);
footer.setBorder(Rectangle.NO_BORDER);
// step1
Document
doc = new Document(rect, 50, 50, 50, 50);
doc.setFooter(footer);
try
{
FileReader
fileRead = new FileReader(txtFilePath);
BufferedReader read = new
BufferedReader(fileRead);
// 設置pdf文件生成路徑 step2
PdfWriter.getInstance(doc, new FileOutputStream(file));
//
打開pdf文件 step3
doc.open();
// 實例化Paragraph
獲取寫入pdf文件的內容,調用支持中文的方法. step4
while (read.ready())
{
// 添加內容到pdf(這里將會按照txt文件的原始樣式輸出)
doc.add(new Paragraph(read.readLine(), setChineseFont()));
}
// 關閉pdf文件 step5
doc.close();
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
/**
* 在pdf文件中添加水印
*
* @param inputFile
原始文件
* @param outputFile 水印輸出文件
* @param waterMarkName
水印名字
*/
private static void waterMark(String inputFile, String
outputFile, String userPassWord, String ownerPassWord,
String waterMarkName, int permission)
{
try
{
PdfReader reader = new PdfReader(inputFile);
PdfStamper stamper = new PdfStamper(reader, new
FileOutputStream(outputFile));
// 設置密碼
stamper.setEncryption(userPassWord.getBytes(), ownerPassWord.getBytes(),
permission, false);
BaseFont base =
BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
BaseFont.NOT_EMBEDDED);
int total = reader.getNumberOfPages() +
1;
// Image image =
Image.getInstance(imageFilePath);
//
image.setAbsolutePosition(200, 400);
PdfContentByte
under;
int j = waterMarkName.length();
char c =
0;
int rise = 0;
for (int i = 1; i < total;
i++)
{
rise = 500;
under =
stamper.getUnderContent(i);
// 添加圖片
//
under.addImage(image);
under.beginText();
under.setColorFill(Color.CYAN);
under.setFontAndSize(base,
30);
// 設置水印文字字體傾斜 開始
if (j >=
15)
{
under.setTextMatrix(200,
120);
for (int k = 0; k < j;
k++)
{
under.setTextRise(rise);
c =
waterMarkName.charAt(k);
under.showText(c +
"");
rise -= 20;
}
}
else
{
under.setTextMatrix(180, 100);
for (int k = 0; k < j; k++)
{
under.setTextRise(rise);
c = waterMarkName.charAt(k);
under.showText(c +
"");
rise -= 18;
}
}
// 字體設置結束
under.endText();
// 畫一個圓
//
under.ellipse(250, 450, 350, 550);
//
under.setLineWidth(1f);
// under.stroke();
}
stamper.close();
}
catch (Exception
e)
{
e.printStackTrace();
}
}
/**
* 設置中文
*
* @return Font
*/
private static Font setChineseFont()
{
BaseFont base =
null;
Font fontChinese = null;
try
{
base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
BaseFont.EMBEDDED);
fontChinese = new Font(base, 12,
Font.NORMAL);
}
catch (DocumentException e)
{
e.printStackTrace();
}
catch (IOException
e)
{
e.printStackTrace();
}
return fontChinese;
}
public static void main(String[] args)
{
generatePDFWithTxt(txtFilePath, pdfFilePath, "123", "水印文字", 16);
}
}
文章參考一些網路博客稍加修改調試,特此申明
http://hi..com/sx_python/item/15081531ad7d1bc21b96965e