Spire.PDF is a professional PDF library applied to creating, writing, editing, handling and reading PDF files without any external dependencies. Get free and professional technical support for Spire.PDF for .NET, Java, Android, C++, Python.

Tue Apr 15, 2025 10:42 am

Hi, paid customers of spire.pdf for java.

I need to write a simple text like this

This is a simple text centered


where the simple word is in bold.

I cannot use the drawString function with the last parameter htmlTags set to true because it is not so stable.

So I should write first "This is a ", then "simple" and then "text centered".

So my question is: how can I manage the x coordinate in writing centered text?

donspa72
 
Posts: 7
Joined: Wed Dec 11, 2024 1:30 pm

Wed Apr 16, 2025 3:50 am

Hello,

Thanks for your inquiry.
We provide a measureString method that can measure the width of a string. For your needs, I uploaded my test code for your reference. If you have further questions, please feel free to write to me.
Code: Select all
PdfDocument doc = new PdfDocument();
PdfPageBase page = doc.getPages().add(PdfPageSize.A4, new PdfMargins(35f));
String firstText = "This is a";
PdfTrueTypeFont firstFont = new PdfTrueTypeFont(new Font("Arial",Font.PLAIN,12));
double width = firstFont.measureString(firstText).getWidth();
PdfSolidBrush titleBrush = new PdfSolidBrush(new PdfRGBColor(Color.BLACK));
String secText = " Bold";
PdfTrueTypeFont secFont = new PdfTrueTypeFont(new Font("Arial",Font.BOLD,12));
double width2 = secFont.measureString(secText).getWidth() + width;
String lastText = " text centered";
String str = "This is a Bold text centered";
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial",Font.BOLD,12));
double width1 = font.measureString(str).getWidth();
PdfTrueTypeFont lastFont = new PdfTrueTypeFont(new Font("Arial",Font.PLAIN,12));
page.getCanvas().drawString(firstText, firstFont, titleBrush, new Point2D.Float((float)page.getClientSize().getWidth()/2 - (float) width1/2, 100));
page.getCanvas().drawString(secText, secFont, titleBrush, new Point2D.Float((float) width + (float)page.getClientSize().getWidth()/2 - (float) width1/2, 100));
page.getCanvas().drawString(lastText, lastFont, titleBrush, new Point2D.Float((float) width2 + (float)page.getClientSize().getWidth()/2 - (float) width1/2, 100));
doc.saveToFile("res.pdf");
doc.dispose();

Sincerely,
William
E-iceblue support team
User avatar

William.Zhang
 
Posts: 757
Joined: Mon Dec 27, 2021 2:23 am

Return to Spire.PDF