image.png (132.6 KB)
想将pdf中的"中国银行" 替换成 “美国银行” 怎么做到
这是我的代码
public class Test {
public static final Set<String> set = new HashSet();
public static void main(String[] args) {
// Open document
Document pdfDocument = new Document("D:\\word_test\\copy_pdf_test.pdf");
replace(pdfDocument,"中国银行","美国银行");
pdfDocument.save("D:\\word_test\\qq.pdf");
}
public static void replace( Document pdfDocument,String source,String target){
TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(source);
// Accept the absorber for all pages of document
pdfDocument.getPages().accept(textFragmentAbsorber);
// Get the extracted text fragments into collection
TextFragmentCollection textFragmentCollection = textFragmentAbsorber.getTextFragments();
// Loop through the fragments
for (TextFragment textFragment : textFragmentCollection) {
textFragment.getRectangle();
textFragment.setInLineParagraph(true);
Position baselinePosition = textFragment.getBaselinePosition();
double xIndent = baselinePosition.getXIndent();
double yIndent = baselinePosition.getYIndent();
if(!set.contains(baselinePosition.getXIndent() + "-" + baselinePosition.getYIndent())){
set.add(xIndent + "-" + yIndent);
// Update text and other properties
textFragment.setText(target);
}
}
}
}