java完整的利用itext5制作pdf、二维码图片插入pdf,并解析pdf中的二维码信息
利用itext5、zxing、QRCore制作pdf、二维码图片插入pdf,并解析pdf中的二维码信息,手机可以实现扫描获取二维码的信息,并进行验证你的解析是否正确。
先是生成二维码图片并插入pdf中
package com.parseImage;import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import java.io.FileOutputStream;
import java.io.IOException;public class CreateBarcodePdf {public static void main(String... args) throws IOException, DocumentException {Document document = new Document();PdfWriter writer = PdfWriter.getInstance(document, new
//pdf输出地址
FileOutputStream("./src/test/resources/scanner.pdf"));document.open();PdfContentByte cb = writer.getDirectContent();BarcodeQRCode barcodeQRCode = new BarcodeQRCode("http://memorynotfound.com", 1000, 1000, null);Image codeQrImage = barcodeQRCode.getImage();codeQrImage.scaleAbsolute(100, 100);document.add(codeQrImage);document.close();}
}
效果图
抽取pdf中二维码图片
package com.parseImage;
import java.io.IOException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
/**
Extracts images from a PDF file.
*/
public class ExtractImages {/**
- PDF to extract images from
*/
//pdf路径
public static final String SOURCE_PDF = “./src/test/resources/scanner.pdf”;
/**
Parses a PDF and extracts all the images.
@param filename the source PDF
@param destination the directory to save images
*/
public void extractImages(String filename, String destination)
throws IOException, DocumentException {
System.out.println("Processing PDF at " + filename);
System.out.println("Saving images to " + destination);PdfReader reader = new PdfReader(filename);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
ImageRenderListener listener = new ImageRenderListener(destination + “/Img”);
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
parser.processContent(i, listener);
}
reader.close();
}
/**
Main method.
@param args no arguments needed
@throws DocumentException
@throws IOException
*/
public static void main(String[] args) throws IOException, DocumentException {
String sourcePDF = SOURCE_PDF;//读取图片地址
String destination = “target”;//图片输出地址
if (args.length > 0) {
sourcePDF = args[0];
if (args.length > 1) {
destination = args[1];
}
}new ExtractImages().extractImages(sourcePDF, destination);
}
- PDF to extract images from
}
效果图
识别二维码图片中的二维码信息
package com.parseImage.parse;import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;import javax.imageio.ImageIO;import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.parseImage.BufferedImageLuminanceSource;public class ParseImage {public static void main(String[] args) throws NotFoundException, IOException {String decode = decode("./target/Img-1.png");//识别图片路径System.out.println(decode)//输出到控制台}public static String decode(String filepath) throws IOException, NotFoundException {BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filepath));LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);Binarizer binarizer = new HybridBinarizer(source);BinaryBitmap bitmap = new BinaryBitmap(binarizer);HashMap<DecodeHintType, Object> decodeHints = new HashMap<DecodeHintType, Object>();decodeHints.put(DecodeHintType.CHARACTER_SET, "UTF-8");Result result = new MultiFormatReader().decode(bitmap, decodeHints);return result.getText();}
}
**控制台信息解析二维码信息**
手机扫描二维码信息
由于官方版本更新过快导致有些类已经改变或者丢失,需要添加自己写的必不可少的两个辅助类。
图片监听
package com.parseImage;
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.pdf.PRStream;
import com.itextpdf.text.pdf.PdfDictionary;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.parser.ImageRenderInfo;
import com.itextpdf.text.pdf.parser.PdfImageObject;
import com.itextpdf.text.pdf.parser.RenderListener;
import com.itextpdf.text.pdf.parser.TextRenderInfo;
public class ImageRenderListener implements RenderListener
{
final String name;
int counter = 100000;
public ImageRenderListener(String name){this.name = name;}public void beginTextBlock() { }public void renderText(TextRenderInfo renderInfo) { }public void endTextBlock() { }public void renderImage(ImageRenderInfo renderInfo){try{PdfImageObject image = renderInfo.getImage();if (image == null) return;int number = renderInfo.getRef() != null ? renderInfo.getRef().getNumber() : counter++;String filename = String.format("%s-%s.%s", name, number, image.getFileType());FileOutputStream os = new FileOutputStream(filename);os.write(image.getImageAsBytes());os.flush();os.close();PdfDictionary imageDictionary = image.getDictionary();PRStream maskStream = (PRStream) imageDictionary.getAsStream(PdfName.SMASK);if (maskStream != null){PdfImageObject maskImage = new PdfImageObject(maskStream);filename = String.format("%s-%s-mask.%s", name, number, maskImage.getFileType());os = new FileOutputStream(filename);os.write(maskImage.getImageAsBytes());os.flush();os.close();}}catch (IOException e){e.printStackTrace();}}}
buffer图片资源
package com.parseImage;import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;import com.google.zxing.LuminanceSource;public class BufferedImageLuminanceSource extends LuminanceSource {private final BufferedImage image; private final int left; private final int top; public BufferedImageLuminanceSource(BufferedImage image) {this(image, 0, 0, image.getWidth(), image.getHeight()); } public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {super(width, height); int sourceWidth = image.getWidth(); int sourceHeight = image.getHeight(); if (left + width > sourceWidth || top + height > sourceHeight) {throw new IllegalArgumentException( "Crop rectangle does not fit within image data."); } for (int y = top; y < top + height; y++) {for (int x = left; x < left + width; x++) {if ((image.getRGB(x, y) & 0xFF000000) == 0) {image.setRGB(x, y, 0xFFFFFFFF); // = white } } } this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY); this.image.getGraphics().drawImage(image, 0, 0, null); this.left = left; this.top = top; } public byte[] getRow(int y, byte[] row) {if (y < 0 || y >= getHeight()) {throw new IllegalArgumentException( "Requested row is outside the image: " + y); } int width = getWidth(); if (row == null || row.length < width) {row = new byte[width]; } image.getRaster().getDataElements(left, top + y, width, 1, row); return row; } public byte[] getMatrix() {int width = getWidth(); int height = getHeight(); int area = width * height; byte[] matrix = new byte[area]; image.getRaster().getDataElements(left, top, width, height, matrix); return matrix; } public boolean isCropSupported() {return true; } public LuminanceSource crop(int left, int top, int width, int height) {return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height); } public boolean isRotateSupported() {return true; } public LuminanceSource rotateCounterClockwise() {int sourceWidth = image.getWidth(); int sourceHeight = image.getHeight(); AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth); BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY); Graphics2D g = rotatedImage.createGraphics(); g.drawImage(image, transform, null); g.dispose(); int width = getWidth(); return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width); } }
pom.xml
请完整的参考我的jar和版本(尤其是版本,因为不同的版本,类可能有改变或者缺失)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.itext.parse.image</groupId><artifactId>parseImage</artifactId><version>0.0.1-SNAPSHOT</version><packaging>war</packaging><dependencies><!-- add all iText Core modules --><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.1.3</version><type>jar</type></dependency><dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>2.3.0</version></dependency><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency><dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.7</version>
</dependency>
</dependencies></project>
附上我的源码连接
http://download.csdn.net/download/qq_36832411/9971701
请尊重原创,如果转载请注明转载自何处,我是一个自学Java的人,我希望能有一群和我一样去自学且痴迷于技术的爱好者,大家可以加我的q群:438581190,希望能一起学习,共同发展
java完整的利用itext5制作pdf、二维码图片插入pdf,并解析pdf中的二维码信息相关推荐
- java代码实现二维码图片的生成和解析
2015年什么最火,二维码,2016年随处可见的是什么,二维码.二维码的历史我们就不探究了,今天分享的是利用Java代码实现二维码的生成和解析.Java代码生成和解析二维码涉及到的东西比较多,还需要引 ...
- 生成二维码图片 插入 pdf
com.itextpdf.text.Image 引用包 获取Image的两种常用方式: 1.本地图片插入如 : String imageUrl = "d://123.png"; I ...
- (二维码处理--2)二维码图片和海报背景进行合成(包含生成二维码)
maven依赖 <dependency><groupId>com.google.zxing</groupId><artifactId>core</ ...
- 项目中使用svg格式的字符串转换图片并把图片插入到word和pdf文档
在用Highcharts做图表展示的时候使用到的功能.提供前端页面以及Java后台对svg格式的字符串转换为具体的图片 废话不多了直接上干货 主要代码 web端 <!DOCTYPE HTML&g ...
- 【PDF转换图片】如何把pdf文件转换成图片?如何把批量pdf文件转换成图片?如何把多目录批量pdf文件转换成图片?如何pdf文件转换成图片不失真不损失清晰度?今天教方法
在工作中常常需要将PDF转换为图片,好多免费但是图片有水印和功能不全的问题. 还有市面上很多软件知识完成了部分的工作,比如只能单个文件转PDF,那么遇到多文件的就只能挨个转么? 还有转换的格式支持的非 ...
- 手机PDF文件转换成图片教程来了,PDF转换器推荐
手机PDF文件怎么转换成图片?你还在用截图的方式来将PDF文件转换成图片吗?虽然确实是一种转换的方法,但是使用过的都会发现转换出来的图片清晰度不高,那该如何高清转换呢?今天小编就给大家推荐一个比较好用 ...
- android socket 简易聊天室 java服务器_利用Socket制作一个简易的Android聊天室
首先制作一个客户端,界面如下: 使用方法:启动后,首先在登录编辑框输入一个昵称,然后点击登录,上面灰色区域是聊天窗,其中会显示你的登录提示,显示其他人发的消息.在的登录成功后,可以在下面的发送编辑框内 ...
- 利用计算机制作多媒体的步骤,【计算机教学论文】计算机教学中多媒体课件的设计与制作(共4966字)...
摘要:从多媒体课件的概念与特点入手,论述大学计算机教学中多媒体课件设计与制作应遵循的基本原则,从整体方案规划.课件设计.课件制作三方面阐述大学计算机教学中多媒体课件设计与制作的流程与方法. 关键词:大 ...
- 二叉搜索树的插入,删除,和中序遍历
构建一个值的类型为int的二叉搜索树,输入N和M,然后进行N次插入操作,每次插入之后进行一次遍历验证代码正确性.然后进行M次删除操作,每次删除之后进行一次遍历验证代码正确性. #include &qu ...
最新文章
- python 终止、结束、退出 代码
- ZYNQ 的三种GPIO :MIO EMIO AXI_GPIO
- 李想称十年后要成为汽车界苹果;雅虎邮箱停服;Linux内核欲采用现代C语言标准 | 极客头条...
- 加速pip下载:更换pip源
- Qt:无法定位程序输入点于动态链接库等。
- 解决 Cannot uninstall 'ipython'. It is a distutils installed project and thus we cannot accurately det
- 系统架构师论文-图书馆网络应用体系安全设计
- Python:实现simpson rule辛普森法则算法(附完整源码)
- c51编译器+linux,C51 开源编译器SDCC学习笔记-安装
- Spring Security oauth2.0微信小程序登录
- YEEZY 350灰橙被叫成灰橘,BOOST V2椰子表示很慷慨
- redis限制set大小_redis set大小限制_微信文件大小限制
- 44道JavaScript送命题
- 小程序服务器还得备案域名,小程序服务器要不要域名备案
- Oracle11g R2相比R1的区别
- Day44-45_Hive高级
- Notification 完整版整合
- vuex的使用说明(个人专用)
- VCS产生vpd波形文件
- nyist最终淘汰赛第一场