- Мне нужно определить конкретный текстовый шаблон
- Затем замените этот текстовый шаблон заранее определенным текстовым значением с тем же форматом текстового шаблона, например шрифтом, цветом шрифта, полужирным шрифтом…
- Я могу идентифицировать текст, замените этот текст предопределенными значениями. Но запись в PDF не удалась.
- Переопределив writeString(String string, List textPositions)of PDFTextStripper
- Результат: PDF-файл, созданный с помощью этого кода, не открывается в формате PDF. Я могу открыть в Word, но формат исходного текста отсутствует.
- С помощью cosArray.add(new COSString(replacedField)); или cosArray.set(…)
- Я вижу только поля в сгенерированных PDF.
public void rewrite(String templatePDFPath) throws IOException {
PDDocument document = null;
Writer pdfWriter = null;
try {
File templateFile = new File(templatePDFPath);
document = PDDocument.load(templateFile);
this.setSortByPosition(true);
this.setStartPage(0);
this.setEndPage(document.getNumberOfPages());
pdfWriter = new PrintWriter(
Utils.getFilePathWithTimeStamp(templatePDFPath).toString());
this.writeText(document, pdfWriter);
} finally {
if (document != null) {
document.close();
}
if (null != pdfWriter)
pdfWriter.close();
// if (null != pdfWriter)
// pdfWriter.close();
}
}
protected void writeString(String string, List textPositions)
throws IOException {
for (int i = 0; i < textPositions.size(); i++) {
TextPosition text = textPositions.get(i);
String currentCharcter = text.getUnicode();
// System.out.println("String[" + text.getXDirAdj() + "," + //
// text.getYDirAdj() + " fs=" + text.getFontSize() // + " xscale=" +
// text.getXScale() + " height=" + // text.getHeightDir() + "
// space=" // +
// text.getWidthOfSpace() + " width=" + text.getWidthDirAdj() + //
// "]" +
// currentCharcter);
}
String replacedString = replaceFields(string.trim());
if (!(string.equals(replacedString))) {
System.out.println(
"Field " + string + " is replaced by value " + replacedString);
// super.writeString(replacedString, textPositions);
super.writeString(replacedString);
}
}
Код для подхода 2 — с помощью cosArray.add или cosArray.set(…)
public List < String > replaceFieldsInCosArray(COSArray cosArray) {
List < String > replacedStrings = new ArrayList < String > ();
String stringsOfCOSArray = "";
for (int cosArrayIndex = 0; cosArrayIndex < cosArray.size(); cosArrayIndex++) {
Object cosObject = cosArray.get(cosArrayIndex);
if (cosObject instanceof COSString) {
COSString cosString = (COSString) cosObject;
stringsOfCOSArray += cosString.getString();
}
}
stringsOfCOSArray = stringsOfCOSArray.trim();
//cosArray.clear();
String replacedField = this.replaceFields(stringsOfCOSArray);
System.out.println("cosText:" + stringsOfCOSArray + ":replacedField:" + replacedField);
cosArray.add(new COSString(replacedField));
if (!stringsOfCOSArray.equals(replacedField)) {
replacedStrings.add(replacedField);
}
Подробнее здесь: https://stackoverflow.com/questions/383 ... fbox-2-0-2