【JAVA秒会技术之玩转PDF】IText转PDF秒会

 ITextPDF秒会


       最近在开发过程中,碰到了这样的需求:图片及相关文字信息,按视觉标准,排版后直接转成PDF。因为之前没接触过,乍一听很懵,感觉会很难。但经过一番网上搜索学习后,发现其实很简单!

(一)Maven引入依赖

注意:一定要按此版本号引入,不然会出现很多错误,包括“中文乱码、中文不输出或直接报错”等异常!

		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itextpdf</artifactId>
			<version>5.4.3</version>
		</dependency>
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itext-asian</artifactId>
			<version>5.2.0</version>
		</dependency>
		<dependency>
			<groupId>com.itextpdf.tool</groupId>
			<artifactId>xmlworker</artifactId>
			<version>5.4.1</version>
		</dependency>
		<dependency>
			<groupId>org.jsoup</groupId>
			<artifactId>jsoup</artifactId>
			<version>1.10.1</version>
		</dependency>

(二)快速入门 —— Hello Word!

package com.netease.test;

import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class ITextTest {
	
	public static void main(String[] args) throws Exception {
		//第一步,创建一个 iTextSharp.text.Document对象的实例:
        Document document = new Document();
        //第二步,为该Document创建一个Writer实例:
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\HelloWorld.pdf"));
        //第三步,打开当前Document
        document.open();
        //第四步,为当前Document添加内容;
        document.add(new Paragraph("Hello World"));  
        //第五步,关闭Document
        document.close();
        System.out.println( "OK!" );
	}

}

C盘下找找,打开你的第一个用ITextTest生成的PDF吧,就这么简单,有没有爱上它?

(三)HTML转PDF之快速入门 —— Hello Word!

1.先写一个简单的HelloWorld.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8"/>
	<title>Insert title here</title>
	</head>
	<body>
		<h1>Hello Word!</h1>
		<h2>Hello Word!</h2>
		<h3>Hello Word!</h3>
		<h4>Hello Word!</h4>
		<h5>Hello Word!</h5>
		<h6>Hello Word!</h6>
		<h7>Hello Word!</h7>
	</body>
</html>

注:此处一定要注意,所有标签最终必须全部封闭!比如<meta charset="UTF-8"/>没有封闭,写成了<meta charset="UTF-8">。转换时,会如下错误:

Exception in thread "main" com.itextpdf.tool.xml.exceptions.RuntimeWorkerException: Invalid nested tag head found, expected closing tag meta.

2.Java代码

import java.io.FileInputStream;
import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

public class ITextTest {
	
	public static void main(String[] args) throws Exception {
	//第一步,创建一个 iTextSharp.text.Document对象的实例:
        Document document = new Document();
        //第二步,为该Document创建一个Writer实例:
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\HelloWorld2.pdf"));
        //第三步,打开当前Document
        document.open();
        //第四步,为当前Document添加内容:
        //document.add(new Paragraph("Hello World"));  
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream("C:\\HelloWorld.html"));
        //第五步,关闭Document
        document.close();
        System.out.println( "OK!" );
	}

}

 C盘下找找,打开你的第二个用ITextTest生成的PDF,看看效果吧:


(四)直接向PDF中写入html代码

package com.netease.test;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontProvider;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

public class PdfTest {
	public static void main(String[] args) {
		try {
			Document document = new Document();
			PdfWriter mPdfWriter = PdfWriter.getInstance(document, new FileOutputStream("C:\\test.pdf"));
			document.open();
			String s = getHtml();
			ByteArrayInputStream bin = new ByteArrayInputStream(s.getBytes());
			XMLWorkerHelper.getInstance().parseXHtml(mPdfWriter, document, bin, null, new ChinaFontProvide());
			System.out.println("OK");
			document.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 拼写html字符串代码
	 * <p>Title: getHtml</p>
	 * @author Liyan
	 * @date   2017年4月1日 下午6:30:30
	 */
	public static String getHtml() {
		StringBuffer html = new StringBuffer();                                                                                                           
        html.append("<div>咆哮的黄河</div>");
        html.append("<div><img src='http://www.photo0086.com/member/5758/pic/2013081217201520156.JPG'/></div>");
		                                                                                                      
		return html.toString();
	}

	/**
	 * 解决中文字体
	 * <p>Title: ChinaFontProvide</p>
	 * @author  Liyan
	 * @date    2017年4月1日 下午6:30:48
	 */
	public static final class ChinaFontProvide implements FontProvider {

		@Override
		public Font getFont(String arg0, String arg1, boolean arg2, float arg3, int arg4, BaseColor arg5) {
			BaseFont bfChinese = null;
			try {
				bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
				//也可以使用Windows系统字体(TrueType)
		        //bfChinese = BaseFont.createFont("C:/WINDOWS/Fonts/SIMYOU.TTF", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED); 
			} catch (Exception e) {
				e.printStackTrace();
			}
			Font FontChinese = new Font(bfChinese, 20, Font.NORMAL);
			return FontChinese;
		}

		@Override
		public boolean isRegistered(String arg0) {
			return false;
		}
	}
}

 注意:IText并不是支持所有前端的标签!


C盘下找找,打开你的第三个用ITextTest生成的PDF,看看效果吧:

 

如果你还有进一步需求,想详细了解IText的强大功能,可以下载下面的两个文档,进行参考!

点击下载:

iText-手札》

iText中文文档》

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Java进行WordPDF的最常用的解决方案是使用iText库。iText是一个开源的Java类库,可以用于创建和操作PDF文件。 首先,需要在Java项目中添加iText库的依赖。可以通过将iText库的JAR文件导入项目的构建路径中来实现。 接下来,使用iText库中提供的类和方法来处理Word文档和生成PDF文件。可以通过以下步骤完成换过程: 1. 首先,使用Apache POI或其他适当的库来读取Word文档的内容。可以使用POI的XWPFDocument类来加载Word文档。 2. 使用iText库创建一个新的PDF文档对象。可以使用com.itextpdf.text.Document类来创建。 3. 将Word文档的内容逐个段落或单词地提取出来,并使用iText提供的相应方法将其添加到PDF文档中。可以使用com.itextpdf.text.Paragraph类来表示段落,并使用com.itextpdf.text.Chunk类来表示单词。 4. 最后,关闭PDF文档对象,将其保存为PDF文件。 下面是一个简单的示例代码,展示如何使用iText将Word换为PDF: ``` import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.poi.xwpf.usermodel.XWPFDocument; import com.itextpdf.text.Document; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; public class WordToPdfConverter { public static void main(String[] args) { try { // 加载Word文档 FileInputStream input = new FileInputStream("input.docx"); XWPFDocument wordDoc = new XWPFDocument(input); // 创建PDF文档 Document pdfDoc = new Document(); PdfWriter.getInstance(pdfDoc, new FileOutputStream("output.pdf")); pdfDoc.open(); // 提取Word文档内容并添加到PDF文档中 for (XWPFParagraph paragraph : wordDoc.getParagraphs()) { String text = paragraph.getText(); pdfDoc.add(new Paragraph(text)); } // 关闭文档 pdfDoc.close(); wordDoc.close(); System.out.println("WordPDF成功!"); } catch (Exception e) { e.printStackTrace(); System.out.println("WordPDF失败!"); } } } ``` 这只是一个简单的示例,你还可以根据具体需求进行更复杂的操作,比如添加标题、表格、图片等。希望这能帮助到你!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值