java完整的利用itext5制作pdf、二维码图片插入pdf,并解析pdf中的二维码信息

二维码解析 同时被 3 个专栏收录
1 篇文章 0 订阅
1 篇文章 0 订阅
2 篇文章 0 订阅

利用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);
      }

}

效果图
这里写图片描述
这里写图片描述
识别二维码图片中的二维码信息

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,希望能一起学习,共同发展

  • 5
    点赞
  • 12
    评论
  • 9
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值