Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace text in a PDF with C#?

Tags:

c#

pdf

I saw a lot of solutions in here but none are clear or good answers.

Here is my simple question, hoping with a straight answer.

I have a PDF file (a template) which is created having text something like this:

{FIRSTNAME} {LASTNAME} {ADDRESS} {PHONENUMBER}

is it possible to have C# code that replace these templates with a text of my choice?

No fields, no other complex stuff.

Is there any Open source library helping me achieve that?

like image 999
Data-Base Avatar asked Aug 22 '11 10:08

Data-Base


People also ask

Is there a Replace function in PDF?

Open a file and click the “Search or replace” button on the upper right corner. Choose “Search & Replace” and then enter the “Initial Text” and the text you want to replace instead. Like ApowerPDF, you can change the text one by one or go to “Replace All” to complete the procedure with one click.


1 Answers

This thread is dead, however I'm posting my solution for other lost souls that might face this problem in the future. Unfortunately my company doesn't allow posting code online so I'll describe the solution :).

So basically what you have to do is use PdfSharp and modify this sample to replace text in stream, but you must take into account that text may be split into many parentheses (convert stream to string to see what the format is).

Then, with code similar to this sample traverse through source pdf page by page and modify current page by searching for PdfContent items inside PdfReference items and replacing text in content's stream.

like image 91
albercik1985 Avatar answered Sep 20 '22 07:09

albercik1985