How to program a text search and replace in PDF files
Asked Answered
M

11

32

How would I be able to programmatically search and replace some text in a large number of PDF files? I would like to remove a URL that has been added to a set of files. I have been able to remove the link using javascript under Batch Processing in Adobe Pro, but the link text remains. I have seen recommendations to use text touchup, which works manually, but I don't want to modify 1300 files manually.

Modeling answered 21/10, 2008 at 0:54 Comment(2)
I know it's really old, but I came along to this problem and you are the first result on google. What did you use at the end?Perse
I used Perl, the CAM::PDF module and the sample changepagestring.pl program as suggested in Chris Dolan's answer. That was a one-time thing, so don't ask me how to do this now ;-)Modeling
T
22

Finding text in a PDF can be inherently hard because of the graphical nature of the document format -- the letters you are searching for may not be contiguous in the file. That said, CAM::PDF has some search-replace capabilities and heuristics. Give changepagestring.pl a try and see if it works on your PDFs.

To install:

 $ cpan install CAM::PDF
 # start a new terminal if this is your first cpan module
 $ changepagestring.pl input.pdf oldtext newtext output.pdf
Teriteria answered 21/10, 2008 at 4:52 Comment(10)
Thanks a lot Chris, for the answer, and for the module on CPAN. That worked nicely for me. Hopefully Google picks up this page, I didn't see the CAM::PDF module in my searches. RogerModeling
for anyone else looking, I tried the trial version of verypdf.com/app/pdf-text-replacer/… and it worked nicely.Ciprian
@Modeling can anyone provide me with a sample example as iam new to perl and i am not aware of how to run that package.Pauli
Only seems to work for simple text, not any TJ boxes with glyph offsets, which seems common ... #220945Elfish
I got Warning: Cannot install CAM-PDF, don't know what it is. using cpan install CAM::PDF worked thoughKynan
@MatthewLock thanks, I changed the answer from "CAM-PDF" to "CAM::PDF". cpan must have changed somewhat in the intervening 13 years :-D As for 3 letters, yeah, there's probably kerning in your doc that breaks the text string up into pieces so CAM::PDF's rudimentary search/replace can't find it.Teriteria
In Debian/unstable, changepagestring does not work at all (I've tried on a single word, so this is simpler than a regexp), even on a simple PDF file obtained with pdflatex, for which pdftotext can find the word. Debian bug 1019979.Striker
@Striker the letters you are searching for may not be contiguous in the file. LaTeX does rather sophisticated kerning so the words are likely not organized as simple strings. Other tools are using heuristics to decide which letters are part of the same word, and mine doesn't do that.Teriteria
@ChrisDolan Yes, additional positive or negative spacing between letters may be needed between letters for justified text in paragraphs. After uncompressing the data streams with qpdf --stream-data=uncompress: [(T)-0.200947(h)-0.599165(e)-333.387(f)-0.599165(ol)-0.800112(l)-0.800112(o)26.9967(w)-0.200947(i)-0.798886(n)-0.599165(g)-332.981(l)-0.798886(i)-0.801337(n)-0.597939(k)-333.785(w)27.8017(or)-0.698413(k)-0.801337(s)-334.415(:)-666.803([)-0.798886(1])-334.812(\()-0.90181(f)-0.597939(o)-26.9832(o:)-0.798886(b)-0.60039(ar)-0.698413(\))-0.90181]TJStriker
@ChrisDolan Actually this paragraph has only one line. So this is just kerning. But it should be possible to detect the small values (see the values less than 1 vs something around 333 for a space).Striker
S
11

I have also become desperate. After 10 PDF Editor installations which all cost money, and no success:

pdftk + editor suffice:

Replace Text in PDF Files

  • Use pdftk to uncompress PDF page streams

    pdftk original.pdf output original.uncompressed.pdf uncompress
    
  • Replace the text (sometimes this works, sometimes it doesn't) within original.uncompressed.pdf

  • Repair the modified (and now broken) PDF

    pdftk original.uncompressed.pdf output original.uncompressed.fixed.pdf
    

(from Joel Dare)

Store answered 28/5, 2009 at 11:48 Comment(1)
This answer doesn't include any instruction for the find/replace operation. Having looked at pdftk, I don't think that tool can do it.Saccharase
J
1

You can use the 'redaction' feature in Adobe Acrobat Pro to find & replace all references in a single document in one step...not sure if it can be automated to multiple steps.

http://help.adobe.com/en_US/Acrobat/9.0/Professional/WS5E28D332-9FF7-4569-AFAD-79AD60092D4D.w.html

Judson answered 28/7, 2010 at 17:44 Comment(0)
C
1

This is just half a solution but I used Touch up combined with AppleScript's support for sending keystrokes to replace a string in thousands of table cells. Depending on how your pages are layout it could work for you. In my case I had to manually insert the cursor in the beginning of every table (tens of tables - quite manageable for a manual process) but after that i replaced thousands of cells automatically.

Clavier answered 18/12, 2012 at 14:7 Comment(0)
C
0

Not sure I would want to do all the work to write the code to modify your 1300 files when there is a program that can do it for you. The other day, I used the Professional version of Infix to batch modify almost 100 files using its "Find and Replace in Files" feature. It works great. I have evaluated other programs in hopes finding an find and replace functionality similar to Microsoft Word. Infix was the only one I found that can do it. Check out: http://www.iceni.com/infix-pro.htm

Clemence answered 7/1, 2011 at 4:13 Comment(0)
W
0

I just finished trying out infix for a text that is comprised of text ladened with diacritics with the hope of generating another text where characters with double and composed diacritics are replaced by alternate with single diacritics. Infix is such definitely a good solution for someone who does not care for the trouble of understanding the working of programmatic solutions. All the request changes were effected. Still need to understand how to effect reflow of words that change the layout of text.

Wallis answered 12/11, 2011 at 13:54 Comment(1)
I found Infix at iceni.com/infix.htm According to their FAQ, Infix Server can find/replace from the command line. It is available for Windows, Linux and MacOS.Saccharase
W
0

The question is for a programmatic solution, but I will still share this free online tool which helped me mass replace text in some PDF files:

http://www.pdfdu.com/pdf-replace-text.aspx

I did not notice any ads or other modifications in the resulting PDF files after replacing the text.

I was not able to make the changes locally with the software I tried. I think the main problem was that I was missing the font used in the PDF and it did not work properly, even with Acrobat Pro. The online tool did not complain and produced a great result.

Waxman answered 14/1, 2015 at 22:26 Comment(2)
The OP asked for a programmatical solution, not a manual one.Nurture
@Nurture You're right, thanks for pointing this out. I edited my answer to make that more clear. I came upon this question in my search for a one-time solution of mass-replacing some text in PDFs. I was okay with a programmatical solution, but nothing I tried worked. That online tool did work, howerver, so I decided to share it anyway.Waxman
H
0

I suggest you may use VeryPDF PDF Text Replacer Command Line software to batch replace text in PDF pages, you can run pdftr.exe to replace text in PDF pages easily, for example,

pdftr.exe -contentreplace "My Name=>Your Name" D:\in.pdf D:\out.pdf

pdftr.exe -searchandoverlaytext "My Name=>Your Name" D:\in.pdf D:\out.pdf

pdftr.exe -searchandoverlaytext "My Name=>D:\temp\myname.png*20*20" D:\in.pdf D:\out.pdf

pdftr.exe -pagerange 1-3 -contentreplace "Old Text=>New Text||VeryPDF=>VeryDOC||My Name=>Your Name" D:\in.pdf D:\out.pdf

pdftr.exe -searchtext "string" C:\in.pdf

pdftr.exe -pagerange 1 -searchtext "string" C:\in.pdf

pdftr.exe -pagerange 1 -searchandoverlaytext "Old Text=>New Text||VeryPDF=>VeryDOC||My Name=>Your Name" D:\in.pdf D:\out.pdf

pdftr.exe -overlaytextfontname "Arial" -overlaytextcolor FF0000 -overlaybgcolor 00FF00 -searchandoverlaytext "Old Text=>New Text||VeryPDF=>VeryDOC||My Name=>Your Name" D:\in.pdf D:\out.pdf

pdftr.exe -opw 123 -upw 456 -contentreplace "Old Text=>New Text||VeryPDF=>VeryDOC||My Name=>Your Name" D:\in.pdf D:\out.pdf

pdftr.exe -searchandoverlaytext "PDFcamp Printer=>VeryPDF Printer" -overlaytextfontsize 8 D:\in.pdf D:\out.pdf

pdftr.exe -searchandoverlaytext "PDFcamp Printer=>VeryPDF Printer" -overlaytextfontsize 80% D:\in.pdf D:\out.pdf

Haematocryal answered 14/7, 2017 at 0:30 Comment(1)
Doesn't seem to be free, windows only.Elfish
E
0

It appears that even with uncompressed pdf's, text is sometimes formatted funky internally. This makes "normal" text command-line replacement, a la sed, not work or not be trivial.

I couldn't find anything that seemed to work with these glyph spacing offsets, i.e. text formatted like this (which seems very common in pdf's), in this example, the word "Other information" is stored like this in a pdf:

 [(O)-16(ther i)-20(nformati)-11(on )]TJ

I wrote a command line tool that is able to replace text embedded within these glyph offsets. It works OK for common use cases. Check it out here. Linux and windows.

First uncompress your pdf, then cd to the checked out git code and:

Syntax

 $ crystal replaceinpdf.cr input_filename.pdf "something you want replaced" "what you want it replaced with" output_filename.pdf

Enjoy! See the git repo for more details. Requests welcome.

Elfish answered 11/6, 2021 at 6:16 Comment(1)
File an issue with all details :)Elfish
V
-1

Although it is quite an old thread. Just wanted to share a Node.js package option to search and replace text in PDF: Aspose.PDF Cloud SDK for Node.js. It is paid product but it provides 150 free monthly API calls.


const { PdfApi } = require("asposepdfcloud");
const { TextReplaceListRequest }= require("asposepdfcloud/src/models/textReplaceListRequest");
const { TextReplace }= require("asposepdfcloud/src/models/textReplace");

// Get Client ID and Client Secret from https://dashboard.aspose.cloud/
pdfApi = new PdfApi("xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxxx");
var fs = require('fs');

const name = "02_pages.pdf";
const remoteTempFolder = "Temp";
//const localTestDataFolder = "C:\\Temp";
//const path = remoteTempFolder + "\\" + name;
//const outputFile= "Replace_output.pdf";


// Upload File
//pdfApi.uploadFile(path, fs.readFileSync(localTestDataFolder + "\\" + name)).then((result) => {  
//                     console.log("Uploaded File");    
//                    }).catch(function(err) {
    // Deal with an error
//    console.log(err);
//});
    
const textReplace= new TextReplace();
        textReplace.oldValue= "origami"; 
        textReplace.newValue= "aspose";
        textReplace.regex= false;

const textReplace1= new TextReplace();
        textReplace1.oldValue= "candy"; 
        textReplace1.newValue= "biscuit";
        textReplace1.regex= false;
    
const trr = new TextReplaceListRequest();
            trr.textReplaces = [textReplace,textReplace1];


// Replace text
pdfApi.postDocumentTextReplace(name, trr, null, remoteTempFolder).then((result) => {    
    console.log(result.body.code);                  
}).catch(function(err) {
    // Deal with an error
    console.log(err);
});

//Download file
//const outputPath = "C:/Temp/" + outputFile;

//pdfApi.downloadFile(path).then((result) => {    
//  fs.writeFileSync(outputPath, result.body);
//    console.log("File Downloaded");    
//}).catch(function(err) {
    // Deal with an error
//    console.log(err);
//});
Venditti answered 7/5, 2021 at 17:36 Comment(0)
E
-1

This library has an extensive support. Check it out.

PDF-LIB

Effeminize answered 16/3, 2022 at 6:59 Comment(1)
Does it do text replacement?Elfish

© 2022 - 2024 — McMap. All rights reserved.