pdfbox获取pdf指定文本附近(可根据距离获取)的图片

引入依赖

      <dependency>
           <groupId>org.apache.pdfbox</groupId>
           <artifactId>pdfbox</artifactId>
           <version>2.0.29</version>
       </dependency>
       <dependency>
           <groupId>com.github.jai-imageio</groupId>
           <artifactId>jai-imageio-core</artifactId>
           <version>1.4.0</version>
       </dependency>
       <dependency>
           <groupId>com.github.jai-imageio</groupId>
           <artifactId>jai-imageio-jpeg2000</artifactId>
           <version>1.3.0</version>
       </dependency>
       <!-- https://mvnrepository.com/artifact/net.sf.cssbox/pdf2dom -->
       <dependency>
           <groupId>net.sf.cssbox</groupId>
           <artifactId>pdf2dom</artifactId>
           <version>2.0.3</version>
       </dependency>

 

 

public class MyPdf extends PDFDomTree {
    private final Map<Integer, Point> textPositions = new TreeMap<>(); // 存储文本坐标
    private final List<ImageResource> nearestImages = new ArrayList<>(); // 存储图片
    private final String searchText = "--"; // 要搜索的文本
    private static PDDocument document;
    public MyPdf() throws IOException {
        super();
    }

    protected void startNewPage(){
        System.out.println("====页码:" + pagecnt);
        super.startNewPage();
    }


    @Override
    protected void renderText(String data, TextMetrics metrics)
    {
        if(data.contains(searchText)){
            System.out.println("====文本:" + data + "," +  ",x:" + (int)metrics.getX() + ",top:" + (int)metrics.getTop() + ",width:" + (int)metrics.getWidth() + ",height:" + (int)metrics.getHeight() );
            textPositions.put(pagecnt,new Point((int)metrics.getX(),(int)metrics.getTop()));
        }
        curpage.appendChild(createTextElement(data, metrics.getWidth()));
    }

//    @Override
//    protected void renderPath(List<PathSegment> path, boolean stroke, boolean fill) throws IOException
//    {
//        PathSegment path1 = path.get(0);
//        System.out.println("====路径1:" + "x1:" + path.get(0).getX1() + ",y1:" + path1.getY1() + ",x2:" + path1.getX2() + ",y2:" + path1.getY2() + ",stroke:" + stroke + ",fill:" + fill);
//        super.renderPath(path, stroke, fill);
//    }

    @Override
    protected void renderImage(float x, float y, float width, float height, ImageResource resource) throws IOException
    {
        System.out.println("====图片:" + "x:" + x + ",y:" + y + ",width:" + width + ",height:" + height);
        curpage.appendChild(createImageElement(x, y, width, height, resource));
        if(textPositions.containsKey(pagecnt)){
            Point point = textPositions.get(pagecnt);
            float textY = point.getY();
            float textX = point.getX();
            float distance = (float) new Point2D.Float(textX, textY).distance(new Point2D.Float(x, y));
            if (distance < 100) {
                nearestImages.add(resource);
            }
        }
    }

    public void parsePdf(PDDocument doc){
        try
        {
            DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
            DOMImplementationLS impl = (DOMImplementationLS)registry.getDOMImplementation("LS");
            LSSerializer writer = impl.createLSSerializer();
            LSOutput output = impl.createLSOutput();
            writer.getDomConfig().setParameter("format-pretty-print", true);
            createDOM(doc);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        try {
            File pdfFile = new File("src/main/resources/2.pdf");
            PDDocument document = PDDocument.load(pdfFile);
            MyPdf pdfDomTree = new MyPdf();
            pdfDomTree.parsePdf(document);
            for (int i = 0; i < pdfDomTree.nearestImages.size(); i++) {
                ImageResource image = pdfDomTree.nearestImages.get(i);
                byte[] imageData = image.getData();
                File outputFile = new File("src/main/resources/image" + (i + 1) + ".png"); // 保存图片的路径
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imageData);
                BufferedImage image1 = ImageIO.read(byteArrayInputStream);
                ImageIO.write(image1,"PNG",outputFile);
                System.out.println("Nearest image " + (i + 1) + " saved at: " + outputFile.getAbsolutePath());
            }

        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}
 class Point {
    private final float x;
    private final float y;

    public Point(float x, float y) {
        this.x = x;
        this.y = y;
    }

    public float getX() {
        return x;
    }

    public float getY() {
        return y;
    }
}

  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
iTextPDF是一个强大的Java库,用于创建、读取和修改PDF文档。如果你想要从已有的PDF文件中获取内容,你可以通过以下步骤操作: ### 安装 iText 首先需要将iText添加到项目的依赖列表中。如果你正在使用Maven项目,可以在`pom.xml`文件中添加以下依赖: ```xml <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>latest_version_here</version> </dependency> ``` 请注意将`latest_version_here`替换为实际的最新版本号。 ### 读取PDF文件 一旦安装并导入了iText的类库,就可以开始读取PDF文件了。以下是一个简单的示例代码片段,展示了如何读取一个PDF文件的内容,并打印出页面文本: ```java import com.itextpdf.io.stream.ByteArrayOutputStream; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfReader; public class ReadPDF { public static void main(String[] args) throws Exception { // 将路径替换为你要打开的PDF文件的实际路径 String path = "path/to/your/pdf/file.pdf"; PdfReader reader = new PdfReader(path); int numberOfPages = reader.getNumberOfPages(); for (int i = 1; i <= numberOfPages; i++) { byte[] pageBytes = getPageContent(reader, i); // 打印页面内容 System.out.println(new String(pageBytes)); } reader.close(); } private static byte[] getPageContent(PdfReader reader, int pageIndex) throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); reader.copyPageContent(outputStream, pageIndex); return outputStream.toByteArray(); } } ``` 在这个例子中,我们首先创建了一个`PdfReader`实例,然后遍历PDF文件的每一页,使用`copyPageContent`方法将页面内容写入到字节数组中,最后关闭了`PdfReader`。 ### 使用场景 读取PDF文件可以应用于多种场景,例如查看报告、审计文档内容、提取信息等。需要注意的是,在处理敏感数据时,应确保遵守相关的隐私法规。 ### 相关问题: 1. **如何在程序中安全地处理PDF文件权限问题?** - 确保用户对PDF文件有适当的访问权限,特别是在远程服务器上存储或处理文件时。 2. **在大型文件上处理时,如何优化性能?** - 分页处理文件,只加载当前显示页面的数据,避免一次性加载整个文件。 3. **iText 是否支持加密的 PDF 文件?** - iText 可以处理加密的 PDF 文件,但需要先解密文件。通常,这涉及到提供正确的密码或解密证书。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值