Like from title I'm trying to write a script that inverts the colors of a bunch of PDF, by using Perl and PDF::API2. I'm not very familiar with perl, I've modified a brief script I found here on stackoverflow, from this post, with the help of chatGPT
how to change all colours in a PDF to their respective complimentary colours; how to make a PDF negative
The code I've come to is the following:
use strict;
use warnings;
use PDF::API2;
use PDF::API2::Basic::PDF::Utils;
my $dirname = '.';
my $filename;
opendir(DIR, $dirname) or die "Could not open $dirname\n";
mkdir("inverted") unless -d "inverted";
while ($filename = readdir(DIR)) {
print("$filename\n");
next unless $filename =~ /\.pdf$/; # Skip files that are not PDFs
my $pdf = PDF::API2->open($filename);
for my $n (1..$pdf->pages()) {
my $p = $pdf->openpage($n);
$p->{Group} = PDFDict();
$p->{Group}->{CS} = PDFName('DeviceRGB');
$p->{Group}->{S} = PDFName('Transparency');
my $gfx = $p->gfx(1); # prepend
$gfx->fillcolor('white');
$gfx->rect($p->mediabox());
$gfx->fill();
$gfx = $p->gfx(); # append
$gfx->egstate($pdf->egstate->blendmode('Difference'));
$gfx->fillcolor('white');
$gfx->rect($p->mediabox());
$gfx->fill();
}
$pdf->saveas("inverted/$filename");
}
closedir(DIR);
It seems to partially work sometimes, some pages are correctly inverted; however sometimes the first half of the page is not inverted, it remains white, like in this pic:
I'd like to fix this, I'd really need a simple script that perform this job, I've also written a script that after that join all the pdf files from multiple files into a single PDF. If anyone has an idea on how to fix it I'll be grateful, I could also upload the result on github if anyone needs this (it's a question has been asked other times too, but I haven't found a script nor in python or other languages that performs this work well, except for a couple of scripts that relies on docker and nodejs in order to install them)
I am debugging this and am confident it has to do with rotation of the pages but I do not understand the details of the problem yet. However, I have this workaround for the test file:
Rotate it 90 degrees with pdftk , then apply the perl script, then rotate it back 90 degrees with pdftk:
$ pdftk test.pdf cat 1-endLeft output test2.pdf $ # run perl script to invert the colors in test2.pdf $ pdftk test2.pdf cat 1-endRight output test3.pdf
After this test3.pdf
seems to be correctly inverted. This workaround might also work for the other files you have.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.