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 May 27, 2025 11:45 am

Hello, I want to replace text in a PDF, and it works.
However, I want to center the replaced text relative to the original text. How do I do that?
I have this problem with both horizontal and vertical text.

To replace the text, I use the following code:

Dim page As PdfPageBase = pdf.Pages(0)
Dim replacer As New PdfTextReplacer(page)
Dim format As New PdfStringFormat()
format.Alignment = HorizontalAlignment.Center
replacer.ReplaceAllText(Text_old, Text_new)

Felix002
 
Posts: 7
Joined: Tue May 27, 2025 11:36 am

Wed May 28, 2025 8:08 am

Hello,

Thanks for your inquiry.
The PdfTextReplacer interface cannot achieve horizontal content centering when replacing text. Please refer to the following code to meet your requirements. If you have any questions, please feel free to write back any time. Thank you in advance.
Code: Select all
Dim page As PdfPageBase = pdf.Pages(0)
Dim replacer As New PdfTextReplacer(page)
Dim format As New PdfStringFormat()
'Set center
format.Alignment = PdfHorizontalAlignment.Center And PdfVerticalAlignment.Middle
Dim finder As New PdfTextFinder(page)
finder.Options.Parameter = Spire.Pdf.Texts.TextFindParameter.WholeWord
'Select text
Dim finds As List(Of PdfTextFragment) = finder.Find(Text_old)
Dim font As New PdfTrueTypeFont(New Font(FontName, FontSize, FontStyle))
Dim brush As PdfBrush = New PdfSolidBrush(Color)
'Replace and set text
For Each find As PdfTextFragment In finds
      Dim rec As RectangleF = find.Bounds(0)
      page.Canvas.DrawRectangle(PdfBrushes.White, rec)
      page.Canvas.DrawString(Text_new, font, brush, rec, format)
Next find


Sincerely,
Tommy
E-iceblue support team
User avatar

Tommy.Tang
 
Posts: 85
Joined: Mon Apr 21, 2025 7:05 am

Tue Jun 03, 2025 6:18 am

Thanks, but that doesn't work for me.
Is it possible to find the text position and move the text in X and Y directions?

Felix002
 
Posts: 7
Joined: Tue May 27, 2025 11:36 am

Tue Jun 03, 2025 10:16 am

Hello,

Thank you for your feedback.
In PDF file, text is drawn based on the specified X and Y coordinates. Our Spire.PDF currently does not allow direct movement of existing text positions. To achieve your goal, you can replace the original keywords with empty string to achieve the effect of 'deletion', then redraw the keywords at the new X and Y coordinates. If you have any other questions, please feel free to write back.

Sincerely,
Tommy
E-iceblue support team
User avatar

Tommy.Tang
 
Posts: 85
Joined: Mon Apr 21, 2025 7:05 am

Tue Jun 03, 2025 11:04 am

Thank you very much for the solution.

But I need several functions for this.

1. How is the center position, font, and font height determined?

2. How is a new vertical text created?

Felix002
 
Posts: 7
Joined: Tue May 27, 2025 11:36 am

Wed Jun 04, 2025 9:15 am

Hello,

Thanks for your feedback. Below are my answers to your questions.
1. The PdfTextFinder interface provides properties for obtaining information such as font name, font size, etc. Sample code shown as below.
Code: Select all
Dim page As PdfPageBase = doc.Pages(0)
Dim pdfTextFinder As New PdfTextFinder(page)
' Find text
Dim pdfTextFragments As List(Of PdfTextFragment) = pdfTextFinder.Find("keyword")
Dim find As PdfTextFragment = pdfTextFragments(0)
' Get font name
Dim fontName As String = find.TextStates(0).FontName
' Get font size
Dim fontSize As Single = find.TextStates(0).FontSize

2. You can define a rectangle, and then draw new text and set the alignment of the text within the rectangle. Please refer to the code below.
Code: Select all
Dim rectangleF As New RectangleF(find.Bounds(0).Location, New SizeF(find.Bounds(0).Width + 10, fontSize + 10))
Dim pdfStringFormat As New PdfStringFormat()
' Horizontal alignment
pdfStringFormat.Alignment = PdfTextAlignment.Center
' Vertical alignment
pdfStringFormat.LineAlignment = PdfVerticalAlignment.Middle
pdfStringFormat.LineLimit = False
' Draw new text
page.Canvas.DrawString("newtext", New PdfTrueTypeFont(New Font(fontName, fontSize), True), PdfBrushes.Black, rectangleF, pdfStringFormat)

3. You can rotate the canvas before drawing the text to achieve the effect of vertical text.
Code: Select all
page.Canvas.RotateTransform(90, find.Positions(0))


Sincerely,
Tommy
E-iceblue support team
User avatar

Tommy.Tang
 
Posts: 85
Joined: Mon Apr 21, 2025 7:05 am

Wed Jun 04, 2025 10:06 am

Tahnks
When I try to test the code, I get an error in "find.Textstates."
Error: "Textstates" is not a member of "PdfTextFragment"

Felix002
 
Posts: 7
Joined: Tue May 27, 2025 11:36 am

Thu Jun 05, 2025 2:41 am

Hello,

Thank you for your feedback.
The 'Textstates' feature was added in recent versions of Spire.PDF for .NET. I recommend installing the latest version(11.5.9) of Spire.PDF for .NET to use. If you have any other questions, please feel free to write back.

Sincerely,
Tommy
E-iceblue support team
User avatar

Tommy.Tang
 
Posts: 85
Joined: Mon Apr 21, 2025 7:05 am

Thu Jun 05, 2025 6:43 am

Thanks, I was able to test the code now.
It's not working as expected.
The horizontal text is arranged one below the other, and if I increase the length, the text is no longer centered.
The vertical text isn't generated.

Felix002
 
Posts: 7
Joined: Tue May 27, 2025 11:36 am

Thu Jun 05, 2025 9:50 am

Hello,

Thank you for your feedback.
To assist us in further investigation, please provide us with your test PDF file and screenshots to demonstrate the desired results. You can attach files here or send them to my email [email protected]. Thank you in advance.

Sincerely,
Tommy
E-iceblue support team
User avatar

Tommy.Tang
 
Posts: 85
Joined: Mon Apr 21, 2025 7:05 am

Fri Jun 06, 2025 4:54 am

Attached are the two PDFs before and after editing and my code.

Code: Select all
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Texts

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim Pfad As String = "S:\Austausch\Fiedler\VB.net\PDFTest_SpirePDF - Kopie"

        ' Create an object of PdfDocument
        Dim pdf As New PdfDocument()

        Dim Text_old As String
        Dim Text_new As String
        Dim Cent As Boolean = False
        Dim Dreh As Integer = 0

        ' Load a PDF document
        pdf.LoadFromFile(Pfad & "\Test.pdf")


        For i = 1 To 4
            If i = 1 Then Text_old = "BL?" : Text_new = "200±3" : Cent = True : Dreh = 0
            If i = 2 Then Text_old = "FD1?" : Text_new = "Ø180" : Cent = True : Dreh = 90
            If i = 3 Then Text_old = "FK1?" : Text_new = "Ø150/8xØ18" : Cent = True : Dreh = 90
            If i = 4 Then Text_old = "DATUM?" : Text_new = Now.Date : Cent = False : Dreh = 0

            Dim page As PdfPageBase = pdf.Pages(0)

            If Cent = False Then
                Dim replacer As New PdfTextReplacer(page)
                replacer.ReplaceAllText(Text_old, Text_new)
            Else
                Dim pdfTextFinder As New PdfTextFinder(page)
                ' Find text
                Dim pdfTextFragments As List(Of PdfTextFragment) = pdfTextFinder.Find(Text_old)
                Dim find As PdfTextFragment = pdfTextFragments(0)
                ' Get font name
                Dim fontName As String = find.TextStates(0).FontName
                ' Get font size
                'Dim LocX As Integer = find.Bounds(0).Location.X
                'Dim LocY As Integer = find.Bounds(0).Location.Y
                'Dim Loc As PointF = (LocX, LocY)
                Dim fontSize As Single = find.TextStates(0).FontSize
                Dim rectangleF As New RectangleF(find.Bounds(0).Location, New SizeF(find.Bounds(0).Width + 20, fontSize))
                Dim pdfStringFormat As New PdfStringFormat()
                ' Horizontal alignment
                pdfStringFormat.Alignment = PdfTextAlignment.Center
                ' Vertical alignment
                pdfStringFormat.LineAlignment = PdfVerticalAlignment.Middle
                pdfStringFormat.LineLimit = False

                Dim replacer As New PdfTextReplacer(page)
                replacer.ReplaceAllText(Text_old, "")

                ' Draw new text
                'page.Canvas.RotateTransform(Dreh, find.Positions(0))
                page.Canvas.DrawString(Text_new, New PdfTrueTypeFont(New Font(fontName, fontSize), True), PdfBrushes.Black, rectangleF, pdfStringFormat)
            End If


        Next


        ' Save the document
        pdf.SaveToFile(Pfad & "\Test2.pdf")
        pdf.Close()

        Process.Start(Pfad & "\Test2.pdf")

    End Sub
End Class


Felix002
 
Posts: 7
Joined: Tue May 27, 2025 11:36 am

Fri Jun 06, 2025 10:21 am

Hello,

Thank you for your feedback.
You can center your text by setting the position and size of rectangleF. The following code is adjusted for your reference:
Code: Select all
Dim rectangleF As New RectangleF(New PointF(find.Bounds(0).Location.X - 15, find.Bounds(0).Location.Y), New SizeF(find.Bounds(0).Width + 30, fontSize))

Regarding the replacement and centering of vertical text, due to the need for coordinate recalculation after canvas rotation, I'm afraid I need more time to investigate and ensure that your expected results are achieved. Thank you for your understanding!

Sincerely,
Tommy
E-iceblue support team
User avatar

Tommy.Tang
 
Posts: 85
Joined: Mon Apr 21, 2025 7:05 am

Thu Jun 12, 2025 6:58 am

Hello,

I'm very sorry to have kept you waiting for so long.
Regarding the replacement issue of your vertical text, you can refer to the following code for adjustment:
Code: Select all
' Get original coordinates and font information
Dim x As Single = find.Bounds(0).X
Dim y As Single = find.Bounds(0).Y
Dim fontName As String = find.TextStates(0).FontName
Dim fontSize As Single = find.TextStates(0).FontSize
' Replace the original text with empty
Dim replacer As New PdfTextReplacer(page)
replacer.ReplaceAllText("FK1?", String.Empty)
' Save canvas state
page.Canvas.Save()
' Rotate counterclockwise by 90 degrees
page.Canvas.RotateTransform(-90)
' Calculate new coordinates after rotation
Dim newX As Single = -y
Dim newY As Single = x
Dim rotatedLocation As New PointF(newX - 50, newY)
' Draw new text
page.Canvas.DrawString(target_text, New PdfTrueTypeFont(New Font(fontName, fontSize), True), PdfBrushes.Black, rotatedLocation)
' Restore canvas state
page.Canvas.Restore()

If you have any other questions later, please contact us in time. Thank you in advance.

Sincerely,
Tommy
E-iceblue support team
User avatar

Tommy.Tang
 
Posts: 85
Joined: Mon Apr 21, 2025 7:05 am

Mon Jun 23, 2025 12:53 pm

Thanks, but it doesn't work as intended and it's not included in the free version, right?

I've now tried a small workaround to achieve centering, which works quite well.
However, I'm having the problem that replacing some text changes the font.

Felix002
 
Posts: 7
Joined: Tue May 27, 2025 11:36 am

Tue Jun 24, 2025 8:04 am

Hi,

Yes, the free version doesn't include the TextStates property. Please download the commercial version (Spire.PDF Pack(Hotfix) Version:11.6.14) to test my code.

As for the changed font issue, did you find this issue when using the replaceAllText method to replace text? Please provide your input and output PDF so that I can investigate in detail. You can send it to my email address ([email protected]).

Sincerely,
Nina
E-iceblue support team
User avatar

Nina.Tang
 
Posts: 1385
Joined: Tue Sep 27, 2016 1:06 am

Return to Spire.PDF

cron