I have an existing pdf where I need to draw a fixed length text without calculating the position for each character. By introducing four spaces between each character I nearly get the desired result but it is still not perfect.
Q1: I am wondering how would you manage a scenario like this, if there are more intelligent ways to achieve the same result.
Here is my sample code and a screenshot of the result PDF file:import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class PdfWriteSample {
public static void main(String[] args) throws IOException {
try (InputStream is = PdfWriteSample.class.getResourceAsStream("/template/Mod_F24_Ordinario.pdf")) {
PDDocument doc = PDDocument.load(is);
PDPage firstPage = doc.getPage(0);
PDFont pdfFont= PDType1Font.HELVETICA_BOLD;
int fontSize = 8;
try (PDPageContentStream contentStream = new PDPageContentStream(doc, firstPage, PDPageContentStream.AppendMode.APPEND,true,true)) {
contentStream.setFont(pdfFont, fontSize);
contentStream.beginText();
contentStream.newLineAtOffset(120,724);
String text = "ABCSKL72E12N408X".replaceAll(".(?!$)", "$0 ");
contentStream.showText(text);
contentStream.endText();
}
doc.save(new File("results/newF24.pdf"));
}
}
}
Q2: To continue drawing text in the next fields, should I go on like this or is there e better way?
contentStream.setFont(pdfFont, fontSize);
contentStream.beginText();
contentStream.newLineAtOffset(117, 724);
contentStream.setCharacterSpacing(9.2f);
contentStream.showText("ABCSKL72E12N408X");
contentStream.endText();
contentStream.beginText();
contentStream.newLineAtOffset(117, 700);
contentStream.setCharacterSpacing(0f);
contentStream.showText("NAME");
contentStream.endText();

setCharacterSpacingorshowTextWithPositioningmight be what you need. Unless this is an acroform (i.e. PDF form fields), then there are better ways.setCharacterSpacingseems a good compromise.doc.getDocumentCatalog().getAcroForm()isnullit means this is not an acroform and the only way to fill the document is by drawing usingshowText(), right?