java 使用库PDF2DOM从dom中删除元素

brccelvz  于 2023-01-01  发布在  Java
关注(0)|答案(1)|浏览(197)

我用Java编写了这段代码,它可以将pdf转换为html,并通过JAX-RS Web服务返回给我,我使用了PDF 2DOM库。我想知道是否有办法访问r类为我创建的div并将其删除,因为它们会使文档在HTML中无法很好地显示。或者,如果没有办法,请从标题中删除名为r的样式。

Document dom = null;
try {
    // load the PDF file using PDFBox
    PDDocument pdf = PDDocument.load(tempFile);
    // create the DOM parser
    PDFDomTree parser = new PDFDomTree();
    // parse the file and get the DOM Document
    dom = parser.createDOM(pdf);

} catch (Exception e) {
    e.printStackTrace();
}

return dom;

PDF2DOM

wgx48brx

wgx48brx1#

最后,我用下面的代码解决了这个问题:

File tempFile = null;
FileOutputStream fos = null;
try {
    tempFile = File.createTempFile("tmp", dr.getId(), null);
    fos = new FileOutputStream(tempFile);
    fos.write(dr.getContent().get(0).getAttachment().getData());
} catch (Exception e) {
    e.printStackTrace();
}

Document dom = null;
try {

    PDDocument pdf = PDDocument.load(tempFile);
    PDFDomTree parser = new PDFDomTree();
    dom = parser.createDOM(pdf);

    NodeList myDivs = dom.getElementsByTagName("div");

    for (int i = 0; i < myDivs.getLength(); i++) {
        NamedNodeMap myMap = myDivs.item(i).getAttributes();
        for (int j = 0; j < myMap.getLength(); j++) {

            String nodeType = myMap.item(j).getNodeName();
            String nodeClass = myMap.item(j).getNodeValue();
            if (nodeType.compareTo("class") == 0 && nodeClass.compareTo("r") == 0) {
                myMap.removeNamedItem(myMap.item(j).getNodeName());
            }

        }
    }

} catch (Exception e) {
    e.printStackTrace();
}

return dom;

相关问题