Essayer d'utiliser Apache PDFBox version 2.0.2 pour un remplacement de texte (avec le code ci-dessous) produit une sortie où peu de caractères ne seraient pas affichés, principalement le majuscule. Par exemple un remplacement par "ABCDEFGHIJKLMNOPQRSTUVWXYZ" la sortie apparaît en pdf comme "ABCDEF HIJKLM OP RST W Y". Est-ce un bug? ou nous avons une solution de contournement pour gérer ces caractères.Apache PDFBox remplace les résultats de texte dans peu de caractères manqués
public static PDDocument replaceText(PDDocument document, String searchString, String replacement) throws IOException {
if (StringUtils.isEmpty(searchString) || StringUtils.isEmpty(replacement)) {
return document;
}
PDPageTree pages = document.getDocumentCatalog().getPages();
for (PDPage page : pages) {
PDFStreamParser parser = new PDFStreamParser(page);
parser.parse();
List tokens = parser.getTokens();
for (int j = 0; j < tokens.size(); j++) {
Object next = tokens.get(j);
if (next instanceof Operator) {
Operator op = (Operator) next;
//Tj and TJ are the two operators that display strings in a PDF
if (op.getName().equals("Tj")) {
// Tj takes one operator and that is the string to display so lets update that operator
COSString previous = (COSString) tokens.get(j - 1);
String string = previous.getString();
string = string.replaceFirst(searchString, replacement);
previous.setValue(string.getBytes());
} else if (op.getName().equals("TJ")) {
COSArray previous = (COSArray) tokens.get(j - 1);
for (int k = 0; k < previous.size(); k++) {
Object arrElement = previous.getObject(k);
if (arrElement instanceof COSString) {
COSString cosString = (COSString) arrElement;
String string = cosString.getString();
string = StringUtils.replaceOnce(string, searchString, replacement);
cosString.setValue(string.getBytes());
}
}
}
}
}
// now that the tokens are updated we will replace the page content stream.
PDStream updatedStream = new PDStream(document);
OutputStream out = updatedStream.createOutputStream();
ContentStreamWriter tokenWriter = new ContentStreamWriter(out);
tokenWriter.writeTokens(tokens);
page.setContents(updatedStream);
out.close();
}
return document;
}
Votre question est parallèle à [cette question] (https://stackoverflow.com/q/34239106/1729265) avec la petite différence que la bibliothèque PDF utilisée était iText. Une grande partie de [ma réponse] (https://stackoverflow.com/a/34315962/1729265) s'applique également ici. – mkl
Merci @mkl, gentil et élaboré .. j'essaie de travailler sur votre suggestion, voudrais toujours aller avec la solution PDFbox si possible. –
Je ne voulais pas vous faire remplacer PDFBox par iText. Ce que je voulais dire par "Une grande partie de ma réponse s'applique ici aussi." étaient les explications pourquoi le problème se produit, et ces explications sont indépendantes de la bibliothèque, ils sont basés sur le fonctionnement de PDF en général. – mkl