使用CAM::PDF编辑PDF时出现“Expected String Closing”错误排查
CAM::PDF文本替换偶发"Expected string closing"错误排查
我使用Perl的CAM::PDF库对单页PDF做文本删除/替换操作,核心代码如下:
my $repl_str = "redacted" my $pdf = CAM::PDF->new($file_name) or die("Couldn't read PDF $file_name: $CAM::PDF::errstr"); my $content = $pdf->getPageContent(1); my $text = $pdf->getPageText(1); my @del_lines; my @lines = split (/ /, $text); # Splits lines into array @lines foreach my $l (@lines) { if ($l =~ /sometexttotemove/ || $l =~ /othertexttoremove/) { push @del_lines, $l; } for (@del_lines) { s/([\(\)])/\\$1/g; # in PDF, parens are pre-escaped so they need an extra backslash my $m = quotemeta; $content =~ s/$m/$repl_str/; } $pdf->setPageContent(1, $content); $pdf->cleanoutput($outfile) or die("Couldn't write ${mrn}_${dt}.pdf: $CAM::PDF::errstr"); }
该代码99.9%的场景下运行正常,但极少会触发以下错误导致脚本终止:
Expected string closing 250 >>...
观察提取的未处理$content内容:
BT 450 20430 Td (sometexttotemove) Tj ET BT 7750 20430 Td (othertexttoremove) Tj ET
替换后的$content内容:
BT 450 20430 Td () Tj ET BT 7750 20430 Td () Tj ET
无论脚本是否崩溃,上述内容变化完全一致。最初怀疑是待删除文本含括号导致问题,但处理转义字符后仍未解决。我已经定位到CAM::PDF源码中的错误位置,但无法理解为何仅部分PDF会触发该错误,求解答。
内容的提问来源于stack exchange,提问作者HPW
相关产品推荐
相关产品推荐

