通常需要用到用于读、写、编辑PDF文件的库,你可以参考下面采用spire.pdf.jar来创建PDF的步骤及方法:
首先需要引入jar包。具体的引入方法可以自行百度搜索。
创建PdfDocument类的对象,并通过PdfDocument.getPages().add()方法添加页码。
定义标题文字。
创建PdfSolidBrush 画刷、PdfTrueTypeFont 字体、PdfStringFormat字符串、Rectangle2D等对象,用于指定字符串绘制效果、字体、格式、绘制区域等。
通过PdfPageBase.getCanvas().drawString(body, font2, brush2, rect, format2)方法将内容绘制到PDF页面。
下面附上详细的代码demo示例:
import com.spire.pdf.*
import com.spire.pdf.graphics.*
import java.awt.*
import java.awt.geom.*
import java.io.*
public class CreatePdfDocumentInJava {
public static void main(String[] args) throws FileNotFoundException, IOException {
//创建PdfDocument对象
PdfDocument doc = new PdfDocument()
//添加一页
PdfPageBase page = doc.getPages().add()
//标题文字
String title = "Java基础语法"
//创建单色画刷对象
PdfSolidBrush brush1 = new PdfSolidBrush(new PdfRGBColor(Color.BLUE))
PdfSolidBrush brush2 = new PdfSolidBrush(new PdfRGBColor(Color.BLACK))
//创建TrueType字体对象
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("宋体", Font.PLAIN, 14), true)
PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("宋体", Font.PLAIN, 10), true)
//创建PdfStringFormat对象
PdfStringFormat format1 = new PdfStringFormat()
format1.setAlignment(PdfTextAlignment.Center)//设置文字居中
//使用drawString方法绘制标题文字
page.getCanvas().drawString(title, font1, brush1, new Point2D.Float((float) page.getActualBounds(true).getWidth() / 2, 0), format1)
//从txt文件读取内容到字符串
String body = readFileToString("C:\\Users\\Administrator\\Desktop\\bodyText.txt")
//创建PdfStringFormat对象
PdfStringFormat format2 = new PdfStringFormat()
format2.setParagraphIndent(20)//设置段首缩进
//创建Rectangle2D对象
Rectangle2D.Float rect = new Rectangle2D.Float(0, 30, (float) page.getActualBounds(true).getWidth(), (float) page.getActualBounds(true).getHeight())
//使用drawString方法在矩形区域绘制主体文字
page.getCanvas().drawString(body, font2, brush2, rect, format2)
//保存到PDF文档
doc.saveToFile("ouput.pdf")
}
//自定义方法读取txt文件内容到字符串
private static String readFileToString(String filepath) throws FileNotFoundException, IOException {
StringBuilder sb = new StringBuilder()
String s = ""
BufferedReader br = new BufferedReader(new FileReader(filepath))
while ((s = br.readLine()) != null) {
sb.append(s + "\n")
}
br.close()
String str = sb.toString()
return str
}
}
import java.io.Fileimport java.io.FileOutputStreamimport java.io.OutputStreamWriterimport java.io.Writerimport java.net.MalformedURLExceptionimport java.net.URLimport org.pdfbox.pdmodel.PDDocumentimport org.pdfbox.util.PDFTextStripperpublic class PdfReader {public void readFdf(String file) throws Exception {// 是否排序boolean sort = false// pdf文件名String pdfFile = file// 输入文本文件名称String textFile = null// 编码方式String encoding = "UTF-8"// 开始提取页数int startPage = 1// 结束提取页数int endPage = Integer.MAX_VALUE// 文件输入流,生成文本文件Writer output = null// 内存中存储的PDF DocumentPDDocument document = nulltry {try {// 首先当作一个URL来装载文件,如果得到异常再从本地文件系统//去装载文件URL url = new URL(pdfFile)//注意参数已不是以前版本中的URL.而是File。document = PDDocument.load(pdfFile)// 获取PDF的文件名String fileName = url.getFile()// 以原来PDF的名称来命名新产生的txt文件if (fileName.length() >4) {File outputFile = new File(fileName.substring(0, fileName.length() - 4)+ ".txt")textFile = outputFile.getName()}} catch (MalformedURLException e) {// 如果作为URL装载得到异常则从文件系统装载//注意参数已不是以前版本中的URL.而是File。document = PDDocument.load(pdfFile)if (pdfFile.length() >4) {textFile = pdfFile.substring(0, pdfFile.length() - 4)+ ".txt"}}// 文件输入流,写入文件倒textFileoutput = new OutputStreamWriter(new FileOutputStream(textFile),encoding)// PDFTextStripper来提取文本PDFTextStripper stripper = nullstripper = new PDFTextStripper()// 设置是否排序stripper.setSortByPosition(sort)// 设置起始页stripper.setStartPage(startPage)// 设置结束页stripper.setEndPage(endPage)// 调用PDFTextStripper的writeText提取并输出文本stripper.writeText(document, output)} finally {if (output != null) {// 关闭输出流output.close()}if (document != null) {// 关闭PDF Documentdocument.close()}}}/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubPdfReader pdfReader = new PdfReader()try {// 取得E盘下的SpringGuide.pdf的内容pdfReader.readFdf("E://SpringGuide.pdf")} catch (Exception e) {e.printStackTrace()}}}import java.io.Fileimport java.io.FileOutputStream
import java.io.IOException
import com.itextpdf.text.*
import com.itextpdf.text.pdf.PdfWriter
public class PdfTest
{
public static void main(String[] args) throws Exception
{
Document pdfDoc = new Document()
// 将要生成的 pdf 文件的路径输出流
FileOutputStream pdfFile =
new FileOutputStream(new File("F:/study/test/firstPdf.pdf"))
// pdf 文件中的一个文字段落
Paragraph paragraph = new Paragraph("My first PDF file with an image ...")
Image image = Image.getInstance("F:/study/test/洛克 李.jpg")
// 用 Document 对象、File 对象获得 PdfWriter 输出流对象
PdfWriter.getInstance(pdfDoc, pdfFile)
pdfDoc.open() // 打开 Document 文档
// 添加一个文字段落、一张图片
pdfDoc.add(paragraph)
pdfDoc.add(image)
pdfDoc.close()
}
}