Posted by a ceTe Software moderator
Hello Ron,
Yes, you can get text width dynamically using getTextWidth method of the Font class without any problem using our DynamicPDF Generator for Java product. Once you calculate the text width then you will need to make sure that you are setting the exact font and font size for the page element through which you are adding text to the PDF. Below is the sample code to calculate the text width and adding the text to the PDF.
String text = "Miss Jones";
Font font=com.cete.dynamicpdf.Font.getCourierBold();
float requiredWidth=font.getTextWidth(text,10);
float requiredWidth1=Font.getCourierBold().getTextWidth(text, 10);
Document document=new Document();
Page page=new Page();
document.getPages().add(page);
Rectangle rectangle=new Rectangle(100,100,requiredWidth,20);
page.getElements().add(rectangle);
//Adding text with the calculated width to the PDF using Label page element.
Label label=new Label(text,100,100,requiredWidth,20);
label.setFont(font);
label.setFontSize(10);
page.getElements().add(label);
document.draw("C:/MyDocument.pdf");
Thanks,
ceTe Software Support Team.