導航:首頁 > 文檔加密 > lowagiepdf

lowagiepdf

發布時間:2022-07-30 18:42:31

Ⅰ 怎麼用java代碼生成pdf文檔

package com.qhdstar.java.pdf;
import java.awt.Color;
import java.io.FileOutputStream;

import com.lowagie.text.Chapter;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Section;
import com.lowagie.text.pdf.PdfWriter;

/**
* 描述:TODO 【JAVA生成PDF】
* <p>
*
* @title GeneratePDF
* @author SYJ
* @email [email protected]
* @date 2013-4-6
* @version V1.0
*/
public class GeneratePDF {

public static void main(String[] args) {

//調用第一個方法,向C盤生成一個名字為ITextTest.pdf 的文件
try {
writeSimplePdf();
}
catch (Exception e) { e.printStackTrace(); }

//調用第二個方法,向C盤名字為ITextTest.pdf的文件,添加章節。
try {
writeCharpter();
}
catch (Exception e) { e.printStackTrace(); }

}

public static void writeSimplePdf() throws Exception {

// 1.新建document對象
// 第一個參數是頁面大小。接下來的參數分別是左、右、上和下頁邊距。
Document document = new Document(PageSize.A4, 50, 50, 50, 50);

// 2.建立一個書寫器(Writer)與document對象關聯,通過書寫器(Writer)可以將文檔寫入到磁碟中。
// 創建 PdfWriter 對象 第一個參數是對文檔對象的引用,第二個參數是文件的實際名稱,在該名稱中還會給出其輸出路徑。
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\ITextTest.pdf"));

// 3.打開文檔
document.open();

// 4.向文檔中添加內容
// 通過 com.lowagie.text.Paragraph 來添加文本。可以用文本及其默認的字體、顏色、大小等等設置來創建一個默認段落
document.add(new Paragraph("First page of the document."));
document.add(new
Paragraph("Some more text on the first page with different color and
font type.", FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new
Color(255, 150, 200))));

// 5.關閉文檔
document.close();
}

/**
* 添加含有章節的pdf文件
*
* @throws Exception
*/
public static void writeCharpter() throws Exception {

// 新建document對象 第一個參數是頁面大小。接下來的參數分別是左、右、上和下頁邊距。
Document document = new Document(PageSize.A4, 20, 20, 20, 20);

// 建立一個書寫器(Writer)與document對象關聯,通過書寫器(Writer)可以將文檔寫入到磁碟中。
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("c:\\ITextTest.pdf"));

// 打開文件
document.open();

// 標題
document.addTitle("Hello mingri example");

// 作者
document.addAuthor("wolf");

// 主題
document.addSubject("This example explains how to add metadata.");
document.addKeywords("iText, Hello mingri");
document.addCreator("My program using iText");

// document.newPage();
// 向文檔中添加內容
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("First page of the document."));
document.add(new Paragraph("First page of the document."));
document.add(new Paragraph("First page of the document."));
document.add(new Paragraph("First page of the document."));
document.add(new
Paragraph("Some more text on the first page with different color and
font type.", FontFactory.getFont(FontFactory.defaultEncoding, 10,
Font.BOLD, new Color(0, 0, 0))));
Paragraph title1 = new
Paragraph("Chapter 1", FontFactory.getFont(FontFactory.HELVETICA, 18,
Font.BOLDITALIC, new Color(0, 0, 255)));

// 新建章節
Chapter chapter1 = new Chapter(title1, 1);
chapter1.setNumberDepth(0);
Paragraph
title11 = new Paragraph("This is Section 1 in Chapter 1",
FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD, new Color(255,
0, 0)));
Section section1 = chapter1.addSection(title11);
Paragraph someSectionText = new Paragraph("This text comes as part of section 1 of chapter 1.");
section1.add(someSectionText);
someSectionText = new Paragraph("Following is a 3 X 2 table.");
section1.add(someSectionText);
document.add(chapter1);

// 關閉文檔
document.close();
}

}

Ⅱ java生成PDF的時候報了 如下異常 怎麼回事

先要把什麼異常發出來看一下才可以
一般會有如下問題
java.lang.NoSuchMethodError: com.lowagie.text.pdf.PdfWriter.setRgbTransparencyBlending(Z)V
at net.sf.jasperreports.engine.export.JRPdfExporter.exportReportToStream(JRPdfExporter.java:455)

JasperReport和iText的版本不匹配。

Ⅲ java怎樣將網頁上面的數據以pdf的格式導出,求代碼

需要用到一個pdf的jar包,去網上下載一個itextpdf.jar。導出pdf的格式都是需要自己用代碼實現的,每一行 ,每一個列是什麼格式,都需要自己寫出來,是不能夠自動生成的,反正很麻煩。我做的一個導出成pdf特定格式的東西,寫了好幾千行代碼。相當頭痛。
package com.dw.mqs.export;

import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.util.Date;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dw.file.WebHelper;
import com.dw.mqs.MqsManager;
import com.dw.mqs.MqsUtilNew;
import com.dw.mqs.ProctItem;
import com.dw.mqs.ProjectBasicItem;
import com.dw.mqs.ProjectConfDetailItem;
import com.dw.mqs.ProjectConfVerItem;
import com.dw.mqs.ProjectConfig;
import com.dw.mqs.ProjectService;
import com.dw.mqs.Util;
import com.dw.system.Convert;
import com.dw.system.gdb.DBResult;
import com.dw.system.gdb.DataRow;
import com.dw.system.gdb.GDB;
import com.dw.user.User;
import com.dw.user.UserManager;
import com.dw.user.UserProfile;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

public class PdfService
{
Document document = new Document(PageSize.A4.rotate(), 50, 50, 50, 50);
ByteArrayOutputStream os = new ByteArrayOutputStream();
PdfWriter pdf = PdfWriter.getInstance(document, os);
Rectangle rect = new Rectangle(36, 54, 559, 788);
pdf.setBoxSize("art", rect);
pdf.setPageEvent(new TableHeader());
document.open();

BaseFont baseArialuni = BaseFont.createFont("res/ARIALUNI.TTF",
BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); // Arial
// unicode字體
Font fontCN = new Font(baseArialuni, 9, Font.NORMAL, Color.BLACK);
Font fontCN8b = new Font(baseArialuni, 9, Font.BOLD, Color.BLACK);
Font fontCN12b = new Font(baseArialuni, 12, Font.BOLD, Color.BLACK);
Font fontCN9b = new Font(baseArialuni, 10, Font.BOLD, Color.BLACK);
Font fontCN9 = new Font(baseArialuni, 10, Font.NORMAL, Color.BLACK);
Font fontCN9b_blue = new Font(baseArialuni, 10, Font.BOLD, Color.BLUE);

PdfPTable table = null;

PdfPCell cell = null;
table = new PdfPTable(relativeWidths);
table.setWidthPercentage(100);
cell = new PdfPCell(new Paragraph(tit + "標題", fontCN12b));
cell.setColspan(root ? 12 : 10);
cell.setHorizontalAlignment(Element.ALIGN_CENTER); // 水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); // 垂直居中
cell.setBorder(Rectangle.NO_BORDER);
table.addCell(cell);

}

Ⅳ 虛心求教,向PDF文件裡面加水印問題,做過的請進來看看

import com.lowagie.text.pdf.PdfStamper;

iTextSharp的確好用,但我加水印一般在初始化的時候寫兩行就行了,不需要這么麻煩,只是圖片得自己做淡一些
if(System.IO.File.Exists("./waterMark/waterMark.JPG") == false)
MessageBox.Show("waterMark載入失敗,請確定文件waterMark.JPG放在waterMark文件夾下!");
else
{
Watermark watermark = new Watermark(iTextSharp.text.Image.getInstance("./waterMark/waterMark.JPG"), wm_left, wm_top);
document.Add(watermark);
}

wm_left, wm_top是水印的位置,從第幾頁開始顯示水印就把上面的代碼加到第幾頁

補充:watermark是iTextSharp里的,不需要其他引用
iTextSharp.text.watermark 檢查是否輸入正確

.\itextsharp-0.04-src\iTextSharp\text\watermark.cs 。。。。。。
或者你可以搜索一下?
代碼全文:
using System;

/*
* $Id: Watermark.cs,v 1.3 2003/05/15 01:49:58 geraldhenson Exp $
* $Name: $
*
* Copyright 2000, 2001, 2002 by Bruno Lowagie.
*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a of the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the License.
*
* The Original Code is 'iText, a free JAVA-PDF library'.
*
* The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
* the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
*
* Contributor(s): all the names of the contributors are added in the source code
* where applicable.
*
* Alternatively, the contents of this file may be used under the terms of the
* LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
* provisions of LGPL are applicable instead of those above. If you wish to
* allow use of your version of this file only under the terms of the LGPL
* License and not to allow others to use your version of this file under
* the MPL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the LGPL.
* If you do not delete the provisions above, a recipient may use your version
* of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MPL as stated above or under the terms of the GNU
* Library General Public License as published by the Free Software Foundation;
* either version 2 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
* details.
*
* If you didn't download this code from the following link, you should check if
* you aren't using an obsolete version:
* http://www.lowagie.com/iText/
*/

namespace iTextSharp.text {
/// <summary>
/// A <CODE>Watermark</CODE> is a graphic element (GIF or JPEG)
/// that is shown on a certain position on each page.
/// </summary>
/// <seealso cref="T:iTextSharp.text.Element"/>
/// <seealso cref="T:iTextSharp.text.Jpef"/>
/// <seealso cref="T:iTextSharp.text.Gif"/>
/// <seealso cref="T:iTextSharp.text.Png"/>
public class Watermark : Image, IElement {

// membervariables

/// <summary> This is the offset in x-direction of the Watermark. </summary>
private float offsetX = 0;

/// <summary> This is the offset in y-direction of the Watermark. </summary>
private float offsetY = 0;

// Constructors

/// <summary>
/// Constructs a <CODE>Watermark</CODE>-object, using an <CODE>Image</CODE>.
/// </summary>
/// <param name="image">an <CODE>Image</CODE>-object</param>
/// <param name="offsetX">the offset in x-direction</param>
/// <param name="offsetY">the offset in y-direction</param>
public Watermark(Image image, float offsetX, float offsetY) : base(image) {
this.offsetX = offsetX;
this.offsetY = offsetY;
}

// implementation of the Element interface

/// <summary>
/// Gets the type of the text element.
/// </summary>
/// <value>a type</value>
public override int Type {
get {
return type;
}
}

// methods to retrieve information

/// <summary>
/// Returns the offset in x direction.
/// </summary>
/// <value>a value</value>
public float OffsetX {
get {
return offsetX;
}
}

/// <summary>
/// Returns the offset in y direction.
/// </summary>
/// <value>an offset</value>
public float OffsetY {
get {
return offsetY;
}
}
}
}

恩,給你發過去了,帶有word教程和示例代碼,國慶快樂

Ⅳ java itextpdf怎麼設置pdf頁眉頁腳

以WPS 2019版本為例:

關於怎麼設置pdf頁眉頁腳,我們推薦您可考慮使用WPS2019來完成,操作步驟如下:

1、打開「PDF文檔」;

2、點擊「插入-頁碼」/「插入-頁眉頁腳」(提示該功能需開通WPS會員使用);

3、可根據需求設置頁面或頁眉頁腳的參數來進行插入。

Ⅵ java 已經獲取pdf代碼,如何把他pdf文件保存到本機 要求用輸出流做

一、iText介紹
iText是著名的開放源碼的站點sourceforge一個項目,是用於生成PDF文檔的一個java類庫。通過iText不僅可以生成PDF或rtf的文檔,而且可以將XML、Html文件轉化為PDF文件。
iText的安裝非常方便,在http://www.lowagie.com/iText/download.html - download 網站上下載iText.jar文件後,只需要在系統的CLASSPATH中加入iText.jar的路徑,在程序中就可以使用iText類庫了。
二、建立第一個PDF文檔
用iText生成PDF文檔需要5個步驟:
①建立com.lowagie.text.Document對象的實例。
Document document = new Document();
②建立一個書寫器(Writer)與document對象關聯,通過書寫器(Writer)可以將文檔寫入到磁碟中。
PDFWriter.getInstance(document, new FileOutputStream("Helloworld.PDF"));
③打開文檔。
document.open();
④向文檔中添加內容。
document.add(new Paragraph("Hello World"));
⑤關閉文檔。
document.close();
通過上面的5個步驟,就能產生一個Helloworld.PDF的文件,文件內容為"Hello World"。
建立com.lowagie.text.Document對象的實例
com.lowagie.text.Document對象的構建函數有三個,分別是:
public Document();
public Document(Rectangle pageSize);
public Document(Rectangle pageSize,
int marginLeft,
int marginRight,
int marginTop,
int marginBottom);
構建函數的參數pageSize是文檔頁面的大小,對於第一個構建函數,頁面的大小為A4,同Document(PageSize.A4)的效果一樣;對於第三個構建函數,參數marginLeft、marginRight、marginTop、marginBottom分別為左、右、上、下的頁邊距。
通過參數pageSize可以設定頁面大小、面背景色、以及頁面橫向/縱向等屬性。iText定義了A0-A10、AL、LETTER、 HALFLETTER、_11x17、LEDGER、NOTE、B0-B5、ARCH_A-ARCH_E、FLSA 和FLSE等紙張類型,也可以通過Rectangle pageSize = new Rectangle(144, 720);自定義紙張。通過Rectangle方法rotate()可以將頁面設置成橫向。
書寫器(Writer)對象
一旦文檔(document)對象建立好之後,需要建立一個或多個書寫器(Writer)對象與之關聯。通過書寫器(Writer)對象可以將具體文檔存檔成需要的格式,如com.lowagie.text.PDF.PDFWriter可以將文檔存成PDF文件, com.lowagie.text.html.HtmlWriter可以將文檔存成html文件。
設定文檔屬性
在文檔打開之前,可以設定文檔的標題、主題、作者、關鍵字、裝訂方式、創建者、生產者、創建日期等屬性,調用的方法分別是:
public boolean addTitle(String title)
public boolean addSubject(String subject)
public boolean addKeywords(String keywords)
public boolean addAuthor(String author)
public boolean addCreator(String creator)
public boolean addProcer()
public boolean addCreationDate()
public boolean addHeader(String name, String content)
其中方法addHeader對於PDF文檔無效,addHeader僅對html文檔有效,用於添加文檔的頭信息。
當新的頁面產生之前,可以設定頁面的大小、書簽、腳注(HeaderFooter)等信息,調用的方法是:
public boolean setPageSize(Rectangle pageSize)
public boolean add(Watermark watermark)
public void removeWatermark()
public void setHeader(HeaderFooter header)
public void resetHeader()
public void setFooter(HeaderFooter footer)
public void resetFooter()
public void resetPageCount()
public void setPageCount(int pageN)
如果要設定第一頁的頁面屬性,這些方法必須在文檔打開之前調用。
對於PDF文檔,iText還提供了文檔的顯示屬性,通過調用書寫器的setViewerPreferences方法可以控制文檔打開時Acrobat Reader的顯示屬性,如是否單頁顯示、是否全屏顯示、是否隱藏狀態條等屬性。
另外,iText也提供了對PDF文件的安全保護,通過書寫器(Writer)的setEncryption方法,可以設定文檔的用戶口令、只讀、可列印等屬性。
添加文檔內容
所有向文檔添加的內容都是以對象為單位的,如Phrase、Paragraph、Table、Graphic對象等。比較常用的是段落(Paragraph)對象,用於向文檔中添加一段文字。
三、文本處理
iText中用文本塊(Chunk)、短語(Phrase)和段落(paragraph)處理文本。
文本塊(Chunk)是處理文本的最小單位,有一串帶格式(包括字體、顏色、大小)的字元串組成。如以下代碼就是產生一個字體為HELVETICA、大小為10、帶下劃線的字元串:
Chunk chunk1 = new Chunk("This text is underlined", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.UNDERLINE));
短語(Phrase)由一個或多個文本塊(Chunk)組成,短語(Phrase)也可以設定字體,但對於其中以設定過字體的文本塊 (Chunk)無效。通過短語(Phrase)成員函數add可以將一個文本塊(Chunk)加到短語(Phrase)中,如:phrase6.add(chunk);
段落(paragraph)由一個或多個文本塊(Chunk)或短語(Phrase)組成,相當於WORD文檔中的段落概念,同樣可以設定段落的字體大小、顏色等屬性。另外也可以設定段落的首行縮進、對齊方式(左對齊、右對齊、居中對齊)。通過函數setAlignment可以設定段落的對齊方式, setAlignment的參數1為居中對齊、2為右對齊、3為左對齊,默認為左對齊。
四、表格處理
iText中處理表格的類為:com.lowagie.text.Table和com.lowagie.text.PDF.PDFPTable,對於比較簡單的表格處理可以用com.lowagie.text.Table,但是如果要處理復雜的表格,這就需要 com.lowagie.text.PDF.PDFPTable進行處理。這里就類com.lowagie.text.Table進行說明。
類com.lowagie.text.Table的構造函數有三個:
①Table (int columns)
②Table(int columns, int rows)
③Table(Properties attributes)
參數columns、rows、attributes分別為表格的列數、行數、表格屬性。創建表格時必須指定表格的列數,而對於行數可以不用指定。
建立表格之後,可以設定表格的屬性,如:邊框寬度、邊框顏色、襯距(padding space 即單元格之間的間距)大小等屬性。下面通過一個簡單的例子說明如何使用表格,代碼如下:
1:Table table = new Table(3);
2:table.setBorderWidth(1);
3:table.setBorderColor(new Color(0, 0, 255));
4:table.setPadding(5);
5:table.setSpacing(5);
6:Cell cell = new Cell("header");
7:cell.setHeader(true);
8:cell.setColspan(3);
9:table.addCell(cell);
10:table.endHeaders();
11:cell = new Cell("example cell with colspan 1 and rowspan 2");
12:cell.setRowspan(2);
13:cell.setBorderColor(new Color(255, 0, 0));
14:table.addCell(cell);
15:table.addCell("1.1");
16:table.addCell("2.1");
17:table.addCell("1.2");
18:table.addCell("2.2");
19:table.addCell("cell test1");
20:cell = new Cell("big cell");
21:cell.setRowspan(2);
22:cell.setColspan(2);
23:table.addCell(cell);
24:table.addCell("cell test2");
運行結果如下:
header
example cell with colspan 1 and rowspan 2 1.1 2.1
1.2 2.2
cell test1 big cell
cell test2
代碼1-5行用於新建一個表格,如代碼所示,建立了一個列數為3的表格,並將邊框寬度設為1,顏色為藍色,襯距為5。
代碼6-10行用於設定表格的表頭,第7行cell.setHeader(true);是將該單元格作為表頭信息顯示;第8行 cell.setColspan(3);指定了該單元格佔3列;為表格添加表頭信息時,要注意的是一旦表頭信息添加完了之後,必須調用 endHeaders()方法,如第10行,否則當表格跨頁後,表頭信息不會再顯示。
代碼11-14行是向表格中添加一個寬度佔一列,長度佔二行的單元格。
往表格中添加單元格(cell)時,按自左向右、從上而下的次序添加。如執行完11行代碼後,表格的右下方出現2行2列的空白,這是再往表格添加單元格時,先填滿這個空白,然後再另起一行,15-24行代碼說明了這種添加順序。
五、圖像處理
iText中處理表格的類為com.lowagie.text.Image,目前iText支持的圖像格式有:GIF, Jpeg, PNG, wmf等格式,對於不同的圖像格式,iText用同樣的構造函數自動識別圖像格式。通過下面的代碼分別獲得gif、jpg、png圖像的實例。
Image gif = Image.getInstance("vonnegut.gif");
Image jpeg = Image.getInstance("myKids.jpg");
Image png = Image.getInstance("hitchcock.png");
圖像的位置
圖像的位置主要是指圖像在文檔中的對齊方式、圖像和文本的位置關系。IText中通過函數public void setAlignment(int alignment)進行處理,參數alignment為Image.RIGHT、Image.MIDDLE、Image.LEFT分別指右對齊、居中、左對齊;當參數alignment為Image.TEXTWRAP、Image.UNDERLYING分別指文字繞圖形顯示、圖形作為文字的背景顯示。這兩種參數可以結合以達到預期的效果,如setAlignment(Image.RIGHT|Image.TEXTWRAP)顯示的效果為圖像右對齊,文字圍繞圖像顯示。
圖像的尺寸和旋轉
如果圖像在文檔中不按原尺寸顯示,可以通過下面的函數進行設定:
public void scaleAbsolute(int newWidth, int newHeight)
public void scalePercent(int percent)
public void scalePercent(int percentX, int percentY)
函數public void scaleAbsolute(int newWidth, int newHeight)直接設定顯示尺寸;函數public void scalePercent(int percent)設定顯示比例,如scalePercent(50)表示顯示的大小為原尺寸的50%;而函數scalePercent(int percentX, int percentY)則圖像高寬的顯示比例。
如果圖像需要旋轉一定角度之後在文檔中顯示,可以通過函數public void setRotation(double r)設定,參數r為弧度,如果旋轉角度為30度,則參數r= Math.PI / 6。
六、中文處理
默認的iText字體設置不支持中文字體,需要下載遠東字體包iTextAsian.jar,否則不能往PDF文檔中輸出中文字體。通過下面的代碼就可以在文檔中使用中文了:
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
com.lowagie.text.Font FontChinese = new com.lowagie.text.Font(bfChinese, 12, com.lowagie.text.Font.NORMAL);
Paragraph pragraph=new Paragraph("你好", FontChinese);

Ⅶ java怎麼輸出pdf格式的文件

java導出pdf需要用到iText庫,iText是著名的開放源碼的站點sourceforge一個項目,是用於生成PDF文檔的一個java類庫。通過iText不僅可以生成PDF或rtf
的文檔,而且可以將XML、Html文件轉化為PDF文件。
iText的安裝非常方便,下載iText.jar文件後,只需要在系統的CLASSPATH中加入iText.jar的路徑,在程序中就可以使用
iText類庫了。
代碼如下:

public class createPdf {
//自己做的一個簡單例子,中間有圖片之類的
//先建立Document對象:相對應的 這個版本的jar引入的是com.lowagie.text.Document
Document document = new Document(PageSize.A4, 36.0F, 36.0F, 36.0F, 36.0F);
public void getPDFdemo() throws DocumentException, IOException{
//這個導出用的是 iTextAsian.jar 和iText-2.1.3.jar 屬於比較老的方法。 具體下在地址見:
//首先
//字體的定義:這里用的是自帶的jar裡面的字體
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
// 當然你也可以用你電腦裡面帶的字體庫
//BaseFont bfChinese = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1",BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
//定義字體 注意在最新的包裡面 顏色是封裝的
Font fontChinese8 = new Font(bfChinese, 10.0F, 0, new Color(59, 54, 54));
//生成pdf的第一個步驟:
//保存本地指定路徑
saveLocal();
document.open();
ByteArrayOutputStream ba = new ByteArrayOutputStream();
// PdfWriter writer = PdfWriter.getInstance(document, ba);
document.open();
//獲取此編譯的文件路徑
String path = this.getClass().getClassLoader().getResource("").getPath();
//獲取根路徑
String filePath = path.substring(1, path.length()-15);
//獲取圖片路徑 找到你需要往pdf上生成的圖片
//這里根據自己的獲取的路徑寫 只要找到圖片位置就可以
String picPath = filePath +"\\WebContent" +"\\images\\";
//往PDF中添加段落
Paragraph pHeader = new Paragraph();
pHeader.add(new Paragraph(" 你要生成文字寫這里", new Font(bfChinese, 8.0F, 1)));
//pHeader.add(new Paragraph("文字", 字體 可以自己寫 也可以用fontChinese8 之前定義好的 );
document.add(pHeader);//在文檔中加入你寫的內容
//獲取圖片
Image img2 = Image.getInstance(picPath +"ccf-stamp-new.png");
//定義圖片在文檔中顯示的絕對位置
img2.scaleAbsolute(137.0F, 140.0F);
img2.setAbsolutePosition(330.0F, 37.0F);
//將圖片添加到文檔中
document.add(img2);
//關閉文檔
document.close();
/*//設置文檔保存的文件名
response.setHeader("Content-
disposition", "attachment;filename=\""+ new String(("CCF會員資格確認
函.pdf").getBytes("GBK"),"ISO-8859-1") + "\"");
//設置類型
response.setContentType("application/pdf");
response.setContentLength(ba.size());
ServletOutputStream out = response.getOutputStream();
ba.writeTo(out);
out.flush();*/
}
public static void main(String[]args) throws DocumentException, IOException{
createPdf pdf= new createPdf();
pdf.getPDFdemo();
}

//指定一個文件進行保存 這里吧文件保存到D盤的text.pdf
public void saveLocal() throws IOException, DocumentException{
//直接生成PDF 制定生成到D盤test.pdf
File file = new File("D:\\text2.pdf");
file.createNewFile();
PdfWriter.getInstance(document, new FileOutputStream(file));

}
}

Ⅷ com.lowagie.text.pdf.BaseFont.getCharBBox(C)

不顯示中文可能是你設置報表時候,設置動態復選框的時候屬性沒有設置,出現亂碼問題,選擇簡體中文就可以了(好像是什麼chinese什麼的來), 後面的不顯示欄位,(如果jar包齊全的情況下)應該是跟資料庫欄位沒有對應吧,注意跟報表裡填寫的欄位要一一對應,大小寫都統一!

Ⅸ 如何利用itext將web頁面生成pdf

一、iText介紹
iText是著名的開放源碼的站點sourceforge一個項目,是用於生成PDF文檔的一個java類庫。通過iText不僅可以生成PDF或rtf的文檔,而且可以將XML、Html文件轉化為PDF文件。
iText的安裝非常方便,在http://www.lowagie.com/iText/download.html - download 網站上下載iText.jar文件後,只需要在系統的CLASSPATH中加入iText.jar的路徑,在程序中就可以使用iText類庫了。
二、建立第一個PDF文檔
用iText生成PDF文檔需要5個步驟:
①建立com.lowagie.text.Document對象的實例。
Document document = new Document();
②建立一個書寫器(Writer)與document對象關聯,通過書寫器(Writer)可以將文檔寫入到磁碟中。
PDFWriter.getInstance(document, new FileOutputStream("Helloworld.PDF"));
③打開文檔。
document.open();
④向文檔中添加內容。
document.add(new Paragraph("Hello World"));
⑤關閉文檔。
document.close();
通過上面的5個步驟,就能產生一個Helloworld.PDF的文件,文件內容為"Hello World"。
建立com.lowagie.text.Document對象的實例
com.lowagie.text.Document對象的構建函數有三個,分別是:
public Document();
public Document(Rectangle pageSize);
public Document(Rectangle pageSize,
int marginLeft,
int marginRight,
int marginTop,
int marginBottom);
構建函數的參數pageSize是文檔頁面的大小,對於第一個構建函數,頁面的大小為A4,同Document(PageSize.A4)的效果一樣;對於第三個構建函數,參數marginLeft、marginRight、marginTop、marginBottom分別為左、右、上、下的頁邊距。
通過參數pageSize可以設定頁面大小、面背景色、以及頁面橫向/縱向等屬性。iText定義了A0-A10、AL、LETTER、 HALFLETTER、_11x17、LEDGER、NOTE、B0-B5、ARCH_A-ARCH_E、FLSA 和FLSE等紙張類型,也可以通過Rectangle pageSize = new Rectangle(144, 720);自定義紙張。通過Rectangle方法rotate()可以將頁面設置成橫向。
書寫器(Writer)對象
一旦文檔(document)對象建立好之後,需要建立一個或多個書寫器(Writer)對象與之關聯。通過書寫器(Writer)對象可以將具體文檔存檔成需要的格式,如com.lowagie.text.PDF.PDFWriter可以將文檔存成PDF文件, com.lowagie.text.html.HtmlWriter可以將文檔存成html文件。
設定文檔屬性
在文檔打開之前,可以設定文檔的標題、主題、作者、關鍵字、裝訂方式、創建者、生產者、創建日期等屬性,調用的方法分別是:
public boolean addTitle(String title)
public boolean addSubject(String subject)
public boolean addKeywords(String keywords)
public boolean addAuthor(String author)
public boolean addCreator(String creator)
public boolean addProcer()
public boolean addCreationDate()
public boolean addHeader(String name, String content)
其中方法addHeader對於PDF文檔無效,addHeader僅對html文檔有效,用於添加文檔的頭信息。
當新的頁面產生之前,可以設定頁面的大小、書簽、腳注(HeaderFooter)等信息,調用的方法是:
public boolean setPageSize(Rectangle pageSize)
public boolean add(Watermark watermark)
public void removeWatermark()
public void setHeader(HeaderFooter header)
public void resetHeader()
public void setFooter(HeaderFooter footer)
public void resetFooter()
public void resetPageCount()
public void setPageCount(int pageN)
如果要設定第一頁的頁面屬性,這些方法必須在文檔打開之前調用。
對於PDF文檔,iText還提供了文檔的顯示屬性,通過調用書寫器的setViewerPreferences方法可以控制文檔打開時Acrobat Reader的顯示屬性,如是否單頁顯示、是否全屏顯示、是否隱藏狀態條等屬性。
另外,iText也提供了對PDF文件的安全保護,通過書寫器(Writer)的setEncryption方法,可以設定文檔的用戶口令、只讀、可列印等屬性。
添加文檔內容
所有向文檔添加的內容都是以對象為單位的,如Phrase、Paragraph、Table、Graphic對象等。比較常用的是段落(Paragraph)對象,用於向文檔中添加一段文字。
三、文本處理
iText中用文本塊(Chunk)、短語(Phrase)和段落(paragraph)處理文本。
文本塊(Chunk)是處理文本的最小單位,有一串帶格式(包括字體、顏色、大小)的字元串組成。如以下代碼就是產生一個字體為HELVETICA、大小為10、帶下劃線的字元串:
Chunk chunk1 = new Chunk("This text is underlined", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.UNDERLINE));
短語(Phrase)由一個或多個文本塊(Chunk)組成,短語(Phrase)也可以設定字體,但對於其中以設定過字體的文本塊 (Chunk)無效。通過短語(Phrase)成員函數add可以將一個文本塊(Chunk)加到短語(Phrase)中,如:phrase6.add(chunk);
段落(paragraph)由一個或多個文本塊(Chunk)或短語(Phrase)組成,相當於WORD文檔中的段落概念,同樣可以設定段落的字體大小、顏色等屬性。另外也可以設定段落的首行縮進、對齊方式(左對齊、右對齊、居中對齊)。通過函數setAlignment可以設定段落的對齊方式, setAlignment的參數1為居中對齊、2為右對齊、3為左對齊,默認為左對齊。
四、表格處理
iText中處理表格的類為:com.lowagie.text.Table和com.lowagie.text.PDF.PDFPTable,對於比較簡單的表格處理可以用com.lowagie.text.Table,但是如果要處理復雜的表格,這就需要 com.lowagie.text.PDF.PDFPTable進行處理。這里就類com.lowagie.text.Table進行說明。
類com.lowagie.text.Table的構造函數有三個:
①Table (int columns)
②Table(int columns, int rows)
③Table(Properties attributes)
參數columns、rows、attributes分別為表格的列數、行數、表格屬性。創建表格時必須指定表格的列數,而對於行數可以不用指定。
建立表格之後,可以設定表格的屬性,如:邊框寬度、邊框顏色、襯距(padding space 即單元格之間的間距)大小等屬性。下面通過一個簡單的例子說明如何使用表格,代碼如下:
1:Table table = new Table(3);
2:table.setBorderWidth(1);
3:table.setBorderColor(new Color(0, 0, 255));
4:table.setPadding(5);
5:table.setSpacing(5);
6:Cell cell = new Cell("header");
7:cell.setHeader(true);
8:cell.setColspan(3);
9:table.addCell(cell);
10:table.endHeaders();
11:cell = new Cell("example cell with colspan 1 and rowspan 2");
12:cell.setRowspan(2);
13:cell.setBorderColor(new Color(255, 0, 0));
14:table.addCell(cell);
15:table.addCell("1.1");
16:table.addCell("2.1");
17:table.addCell("1.2");
18:table.addCell("2.2");
19:table.addCell("cell test1");
20:cell = new Cell("big cell");
21:cell.setRowspan(2);
22:cell.setColspan(2);
23:table.addCell(cell);
24:table.addCell("cell test2");
運行結果如下:
header
example cell with colspan 1 and rowspan 2 1.1 2.1
1.2 2.2
cell test1 big cell
cell test2
代碼1-5行用於新建一個表格,如代碼所示,建立了一個列數為3的表格,並將邊框寬度設為1,顏色為藍色,襯距為5。
代碼6-10行用於設定表格的表頭,第7行cell.setHeader(true);是將該單元格作為表頭信息顯示;第8行 cell.setColspan(3);指定了該單元格佔3列;為表格添加表頭信息時,要注意的是一旦表頭信息添加完了之後,必須調用 endHeaders()方法,如第10行,否則當表格跨頁後,表頭信息不會再顯示。
代碼11-14行是向表格中添加一個寬度佔一列,長度佔二行的單元格。
往表格中添加單元格(cell)時,按自左向右、從上而下的次序添加。如執行完11行代碼後,表格的右下方出現2行2列的空白,這是再往表格添加單元格時,先填滿這個空白,然後再另起一行,15-24行代碼說明了這種添加順序。
五、圖像處理
iText中處理表格的類為com.lowagie.text.Image,目前iText支持的圖像格式有:GIF, Jpeg, PNG, wmf等格式,對於不同的圖像格式,iText用同樣的構造函數自動識別圖像格式。通過下面的代碼分別獲得gif、jpg、png圖像的實例。
Image gif = Image.getInstance("vonnegut.gif");
Image jpeg = Image.getInstance("myKids.jpg");
Image png = Image.getInstance("hitchcock.png");
圖像的位置
圖像的位置主要是指圖像在文檔中的對齊方式、圖像和文本的位置關系。IText中通過函數public void setAlignment(int alignment)進行處理,參數alignment為Image.RIGHT、Image.MIDDLE、Image.LEFT分別指右對齊、居中、左對齊;當參數alignment為Image.TEXTWRAP、Image.UNDERLYING分別指文字繞圖形顯示、圖形作為文字的背景顯示。這兩種參數可以結合以達到預期的效果,如setAlignment(Image.RIGHT|Image.TEXTWRAP)顯示的效果為圖像右對齊,文字圍繞圖像顯示。
圖像的尺寸和旋轉
如果圖像在文檔中不按原尺寸顯示,可以通過下面的函數進行設定:
public void scaleAbsolute(int newWidth, int newHeight)
public void scalePercent(int percent)
public void scalePercent(int percentX, int percentY)
函數public void scaleAbsolute(int newWidth, int newHeight)直接設定顯示尺寸;函數public void scalePercent(int percent)設定顯示比例,如scalePercent(50)表示顯示的大小為原尺寸的50%;而函數scalePercent(int percentX, int percentY)則圖像高寬的顯示比例。
如果圖像需要旋轉一定角度之後在文檔中顯示,可以通過函數public void setRotation(double r)設定,參數r為弧度,如果旋轉角度為30度,則參數r= Math.PI / 6。
六、中文處理
默認的iText字體設置不支持中文字體,需要下載遠東字體包iTextAsian.jar,否則不能往PDF文檔中輸出中文字體。通過下面的代碼就可以在文檔中使用中文了:
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
com.lowagie.text.Font FontChinese = new com.lowagie.text.Font(bfChinese, 12, com.lowagie.text.Font.NORMAL);
Paragraph pragraph=new Paragraph("你好", FontChinese);

小結
iText還有很多高級的功能,這里就不一一介紹了,具體開發時可參考發布的文檔。總的來說,iText是一套java環境下不錯的製作PDF的組件。因為iText支持jsp/javabean下的開發,這使得B/S應用中的報表問題能得到很好的解決。由於iText畢竟不是專門為製作報表設計,所有報表中的內容、格式都需要通過寫代碼實現,相對於那些專業的支持可視化設計的報表軟體來說,編程的工作量就有一定程度的增加。

閱讀全文

與lowagiepdf相關的資料

熱點內容
匯編程序的偽指令 瀏覽:803
蘋果7怎麼更新app 瀏覽:318
c語言常用演算法pdf 瀏覽:960
編程如何讓畫面動起來 瀏覽:865
大齡女程序員未來發展 瀏覽:976
數學書籍pdf 瀏覽:506
加密門禁卡寫入成功無法開門 瀏覽:464
齒輪傳動pdf 瀏覽:52
alpinelinux 瀏覽:150
手機端app的掃碼功能在哪裡 瀏覽:227
少兒編程中小班英語教案 瀏覽:452
鎖屏密碼加密手機怎麼解除 瀏覽:205
linuxlostfound 瀏覽:135
征途伺服器ip地址 瀏覽:330
git提交代碼命令行 瀏覽:165
什麼叫瀏覽器伺服器結構 瀏覽:157
於謙聊天哪個app 瀏覽:449
小鵬汽車nlp演算法工程師薪資 瀏覽:881
代碼加密與隱藏 瀏覽:649
fordfulkerson演算法 瀏覽:352