Remove lines between patterns nearest another pattern - awk

I'm trying to remove certain objects from a PDF file. The objects all look like this:
40 0 obj
<<
/PieceInfo
/Subtype /Form
/Resources
<<
/Font
<<
/Fm1 35 0 R
>>
>>
/Type /XObject
/BBox [0 -22.5 131.05 0]
/Length 601
/Matrix [1 0 0 1 0 0]
>>
stream
. . .
A bunch of compressed gibberish here
. . .
endstream
endobj
What I found to work without breaking the PDF document is deleting the stuff between obj, stream, and endstream.
Is there a way in sed or awk to look for lines containing /Form, and then deleting everything between the nearest obj above and stream below, and that stream and the endstream below it, so that the final result looks like this:
40 0 obj
stream
endstream
endobj

Given:
$ echo "$pdf"
40 0 obj
<<
/PieceInfo
/Subtype /Form
/Resources
<<
/Font
<<
/Fm1 35 0 R
>>
>>
/Type /XObject
/BBox [0 -22.5 131.05 0]
/Length 601
/Matrix [1 0 0 1 0 0]
>>
stream
. . .
A bunch of compressed gibberish here
. . .
endstream
endobj
You can use perl:
$ echo "$pdf" | perl -0777 -lne 'print "$1$2$3\n" if /(^.*(?<=\bobj)\s*\R)[\s\S]*?\/Form[\s\S]*?^(stream\s*^)[\s\S]*?^(endstream\s+endobj)/m'
40 0 obj
stream
endstream
endobj
Demo and explanation of regex

perl -0777 -pe 's/(?<=obj)[\s\S]+?\/Form[\s\S]+?\n(?=endstream)/\nstream\n/g' pdf
There are a LOT of ways this regex can backfire (The key issue is "obj" or "endstream" appearing midstream or those fields or "/Form" being missing). You'll need a full script for something production quality, in which case you would definitely need to "show your work" to get help. Also you may need to remove or change the \n before (?=endstream) for an actual PDF. I'm not familiar with the line end characters it uses.
The jist, as a glob, would be that it looks for obj*/Form*endstream, and then clobbers everything not in a lookaround (?[etc]), and it manually readds the stream line.

awk may also do the job,
awk '/[^end]obj/||/[end]*stream/{print;if(d==1){s=""}d=1;next}{s=s $0}END{print s}' pdf
Brief explanation,
/[^end]obj/||/[end]*stream/: locate the string 'obj', 'stream', and 'endstream'
If above string is existed in the line, print it and enable the flag d
If the d is already enabled, clear the buffer str
Print the str in the end

This might work for you (GNU sed):
sed -r '/\<obj\>/{n;:a;/\<endobj\>/!{N;ba};s/.*\<(stream)\>.*\<(endobj)\>/\1\n\2/}' file
Gather up the lines between obj and endobj and remove the parts either side of stream.

$ cat tst.awk
$NF == "endobj" {
print (obj ~ "/Form" ? "stream" ORS "endstream" : obj)
obj = ""
inObj = 0
}
inObj { obj = (obj == "" ? "" : obj ORS) $0 }
!inObj { print }
$NF == "obj" { inObj = 1 }
$ awk -f tst.awk file
40 0 obj
stream
endstream
endobj

Related

About the /Catalog object in a pdf file

I see the following objects in a pdf file. It is clear that 16875 is the top /Pages and 16876 is a dictionary of all the link destinations in the pdf. I only see one object with the type /Catalog in the pdf.
Is it always the case that there is only one /Catalog object which contains a pointer to a top /Pages object and a pointer to an object of all the link destinations?
119038 0 obj
<</Type /Catalog
/Pages 16875 0 R
/Dests 16876 0 R
/MarkInfo <</Type /MarkInfo
/Marked true>>
/StructTreeRoot 16877 0 R>>
endobj
16876 0 obj
<</05_preface [11 0 R /XYZ 34.005386 763.99994 0]
/sec1 [339 0 R /XYZ 34.005386 400.67438 0]
/fn1 [339 0 R /XYZ 339.52963 268.5553 0]
...
16875 0 obj
<</Type /Pages
/Count 1603
/Kids [16871 0 R 16872 0 R 16873 0 R 16874 0 R]>>
endobj
Is it always the case that there is only one /Catalog object which contains a pointer to a top /Pages object and a pointer to an object of all the link destinations?
There can be an arbitrary number of dictionaries with type Catalog in a PDF. The one that is relevant is the one referenced as Root from the trailer.
Beware, though, the Dests only contain the named destinations, not necessarily all of them.

How to properly position and activate a hyperlink in PDF?

I'm trying to write a code which adds hyperlinks to existing PDF document.
I've tried to do that by following PDF 32000 specification but seems that I'm missing something.
PDF viewer shows my link annotations and changes the mouse pointer to "finger" when hovering over them, but no URLs are shown, and clicking on them doesn't do anything.
PDF contents are shown below.
Page:
/Type/Page
/Parent 1 0 R
/MediaBox[0 0 594.75 841.5]
/Contents 7 0 R
/Resources 8 0 R
/Annots [5 0 R 6 0 R] % added by me
First annotation (for "Google", #5):
/Type /Annot
/Subtype /Link
/Rect [60.0 779.25 150.0 767.25]
/BS
<<
/W 2 % should be 0, set to 2 to be able to see the annotation's position
>>
/F 4
/A
<<
/Type /Action
/Subtype /URI
/URI (https://google.com)
>>
Second annotation (for "DuckDuckGo", #6):
/Type /Annot
/Subtype /Link
/Rect [342.0 694.5 432.0 682.5]
/BS
<<
/W 2 % should be 0, set to 2 to be able to see the annotation's position
>>
/F 4
/A
<<
/Type /Action
/Subtype /URI
/URI (https://duckduckgo.com)
>>
Content stream:
1 0 0 -1 36.0 841.5 cm
-100 Tz
q
/Font3 -9.0 Tf
0.0 0.0 0.0 rg
24.0 62.25 90.0 12.0 re W n
BT
1 0 0 1 0 0 Tm
24.75 69.75 Td
(Google) Tj
ET
Q
q
/Font3 -9.0 Tf
0.0 0.0 0.0 rg
306.0 147.0 90.0 12.0 re W n
BT
1 0 0 1 0 0 Tm
306.75 154.5 Td
(DuckDuckGo) Tj
ET
Q
This code produces the following result:
Generated PDF file is available here.
I took a look on the code the Microsoft Word produces for the links, and it looks pretty much the same (except minification and structural parent; this code works, but mine is not):
/Subtype/Link/Rect[ 69.75 697.51 113.16 720] /BS
<<
/W 0
>>
/F 4/A
<<
/Type/Action/S/URI/URI(https://google.com/)
>>
/StructParent 0
Any advice will be much appreciated.
Your action dictionary looks like this:
<<
/Type /Action
/Subtype /URI
/URI (https://google.com)
>>
If you lookup ISO 32000-1 section 12.6.2 Action Dictionaries, though, you'll see that the type of action is not the value of Subtype but instead of S:
S
name
(Required) The type of action that this dictionary describes; see Table 194 for specific values.
(ISO 32000-1 Table 193 – Entries common to all action dictionaries)
Thus, in your Action dictionary (not in the surrounding Annot dictionary, though!) replace /Subtype by /S:
/Type /Annot
/Subtype /Link %<------------- not here
/Rect [342.0 694.5 432.0 682.5]
/BS
<<
/W 2 % should be 0, set to 2 to be able to see the annotation's position
>>
/F 4
/A
<<
/Type /Action
/S /URI %<------------- but here
/URI (https://duckduckgo.com)
>>
You have to parse the page content and process all operators that affect text position in order to compute the exact position of Google and DuckDuckGo. Then place the link annotations at the computed positions.

How to program a circle of radius r and center x,y with annotation box positioned bottom,left of x,y using PURE PDF 1.7 specification

I am looking for a way to draw a dot (or small circle) that is an internal "annotation" link to a popup box in a PDF using specification 1.7...
TCPDF does this internally, with code like... see: https://tcpdf.org/examples/example_036/
2 0 obj
<< /ProcSet [/PDF /Text /ImageB /ImageC /ImageI] /Font << /F1 3 0 R /F2 4 0 R /F3 6 0 R >> /XObject << /XT5 5 0 R /I0 11 0 R >> >>
endobj
7 0 obj
<</Type /Annot /Subtype /Text /Rect [235.275591 737.008110 263.622047 765.354567] /Contents (þÿ
I am looking for a solution that does this directly. That is, explaining how the PDF language creates the trigger object (e.g., the circle), and the annotation object (e.g., the popup box), and how the internal linking works.

How to create pdf-file and save to the server?

I want to do is to create the pdf report using jsreport with web api. All I have got is the response from jsreport server as the pdf content in the following format:
%PDF-1.4 1 0 obj << /Title (þÿ) /Creator (þÿ) /Producer (þÿQt 4.8.4 \(C\) 2011 Nokia Corporation and/or its subsidiary\(-ies\)) /CreationDate (D:20151118135420+05'45') >> endobj 3 0 obj << /Type /ExtGState /SA true /SM 0.02 /ca 1.0 /CA 1.0 /AIS false /SMask /None>> endobj 4 0 obj [/Pattern /DeviceRGB] endobj 5 0 obj << /Type /Page /Parent 2 0 R /Contents 8 0 R /Resources 10 0 R /Annots 11 0 R /MediaBox [0 0 595 842] >> endobj 10 0 obj << /ColorSpace << /PCSp 4 0 R /CSp /DeviceRGB /CSpg /DeviceGray >> /ExtGState << /GSa 3 0 R >> /Pattern << >> /Font << /F6 6 0 R /F7 7 0 R >> /XObject << >> >> endobj 11 0 obj [ ] endobj 8 0 obj << /Length 9 0 R /Filter /FlateDecode >> stream xÕOYrÄïý)úl`4,²Ù$ÃÀF2àÁðÁðÁõÚXx÷à¯ïÈî.Uvñ,;ÀÎ+_½?ù2###üÇßþýþ?ÿvÿãûßþçþ÷Ó¿ßÿv7ܯþùa¸_ïïwûíýïÜ}¾ÿ|÷ëݯOÿýåßïVïvÛÕñ?_ÿò·þa=|ùÒósåo¿ÿõîÇã/Þ?ùíý??ý¯ÿ»_ßÿÓÓþrÿ¯ÿöô¯?~çø?î¶ý»Ãá°ßýà¿Ç¬Þ­a·Ú®OÿÇ*üùøÿºû¿»ÿë×A?®VÍÃÃf{ôøÏß;èÏ/_¾þ3þjò·¿üûÃîþé³ÿý»?a¯_ýùÌþt÷ãÇÇûÍãý§?ß¿ì/ÿúôÇÝÕ8ÜúÓýß?-ùð÷þr·þ2Ó'ë¯ ¯l¾~r8óÁÃñ;¯l¿~²ýàqúÁîøËÃë'ûãSFç0ý¡e}æ¹Êw~>þ³cóùÒû0U¿$¾õücx͸*Ǧ"þR|ñøSáÁÃöÑpÚÁÚ3S<·q>|z:Ü=góq½Îa=¡ÙO¾éÙÌ÷xzþn½{wü£á&=ì eôù7÷Êîaÿnûõ&ùzLÿ8þVòr1½Î÷Ü1ßA¹jôpß8ÃñòX¯ÎÙ©øIÂVhÖ-Ìë6l§V(~ºòv©xÅÏßq±ó?ã0-25$O/ò¸Únvô³åý±`?¾g¨ß{׳ÇqøÖ Fàiï.Ô£KµîÀuÜßõg6ñh áöO ¿ó~zZãw׿ó|2G¿´?ñÓáâe-ýtxÄ/Ñ »ðW>ÌÃá;ûðNa®ÂªÄÕ_Kg/l<Þ!á+qüq%o;¦£ ?ésÏâÍß1LÌKXÿ÷a8ñ¥âÄ©»f:oøãütxÞ°iOãùáñáùç>]û~6<¿²îãv;ãOaöyûd5hÿ8Q ×ÓYÛO83æ v.ýÃêì¼Æ1>LmDxÞ¾Ï ¯µ[§ÿ½Ú<ÿÜ05Zëéµñ&âh-}g7ýà¸à#ñð¶9-=#\!ÇӹŠNð¹ ãøHã8ù¿#Ó6L¿~6ÌizÇté¯Ä>#þðаcÂ8Âò:sgÞîOø°´Ra×I =üJxhøÙ°Ó}ùì¸lôþøå¤Â)~wUj82áð0Í<ôéF ç0qÊ·åSÖ²þºqù§s8v{¼ã¬ðÚ3óÓtìü³áí¦Ï`Û0Ìa§²nª8ôðaµÑü 7Wõ`Aø]²V¨Ù Zof7 n¥8SÓg:¼v8äaø8"½Õ§%-|c½qíf0ЧP%àç<¸º_ôÆË -¦£~'C¸Ó¾ sX¿f0¬CÝrƾeâ#=N{8aË S¼l3nݺ?wHXÌ°1îGr·-z,GQ¹ùõ9G÷#~%ÌXp8è ËÀ±wX0|²KÃ{½BËýÆNð%^GpÙp(¡C°CÅK3sË6{hÙÝì/Ca¦Âé <³#_ûq5~ïõöîµ éH}Kù¸ÃÏ^ÉH0I}ÞS a°§Î`æw +<w<0=#°(o*üÄyoÇþ°!]oÂërÀQ_aÓu(ñ³Sw qû c«#Ø×_ÆVRøú$QKÖìÊÐÉfoðq3ûWkÁùV4Dçñ+xP,y !ELè`gÌçâï²WNßWÕU°ðAø ÁÄIÅ=®.ï¡°v[:Ë×ù%ì/?2ÇN` ðëò3ØáóÀ§.<#¸Zg&ìÁãtî¯Øv!ÁÃç!ø ìr`¸3-ubdxb,2½uã¼!ïr¨LHN|}¾|³Ï·öù TÂMä+]ýàì7>=r çâ½ÀN_=XfO§×+HXæ?µämä 5Ï0a`ÁmâÚ:Èã³,áÔ¯¸ø³* å ñfT(í%lÙx¤LæIõÁÕ·ÄÚOÜdÃÌ.$G&(|Ä8fd7áu Øá µøÎ>ÉqzµõKYA©:þ= 4ÊÄÙ)XrÓÿ®=­ØëðÄÐ Ü\à¬ÀLg_]pøêì° ×æò ÍvøÆXçLÀùUî²±HÕcÁDØʶ`h¾.#bJº#n è ÖÆ$üÞÿ<elÕy3;*Ð/ÔFÔ«ú\kÖ/;÷ú¼ØÌ^Îùfÿð¥àâ ·_Â#qÊNÀæ8:g$2 ½G¯^DêHXgJ,õ[J ¾»Ä[®Ûì'T´õåéáðÅ#NdàùípÊùeNã1öÎøÚH%Ñé4^H×8¬&ÿ ;\·â(da÷v½ÒAÆ,b_ Ù5z­tv°Â;;%w.S&×¢8!j·ÃhO õÌdT¯T'/Ëà qnQÿt Àm·[ 7B&ØÔ]âõTéMqQG ±¬® $t OaIÔ}Ä55ºZïX¬+g3¦9¹Ç®cRk dh*ËÜ<c3g½Ù }-±àâº2.Öj¡¥2©²ïI¥R½'5Bi¸!{<7!ë['ê ø¬B å<§ \9N¸¿î£¡.nw2'¸¥ú5äëæ *ðòÕÙ1ÍÅ0lAÉáX¼l(ÄoÑá#Âuæ+kØA3 ƺ<váó^gä*.S&à¹KTÍ®÷óÈ"ë²r_¿:«À¼ ¢%ZâKßRà'x0uÃa^)U¶²·'Töð¶s¼ZýoTx,962¼tB®¬Nsã0Ð/" 5o½à0-$ÜÆ·£rZMUËù*IÐ ëØ ×w ÂÝæD¯!Æ°¶É+qB^UV¹^è'D#'Ú1G|92`ç,-DaÆp®#Ç¥P(Æ7Ñ;ÅÁCGôx]Ci¸Ò¢Cgo¾ !Á¯/ì¹Øÿ¿Loadn;ág5k¶mT{BëË!ú¿#v¹.MÍüH£Rû³¬%!¸K°7¯*ÆÁãfÓjàM%Z8ÔqqÁTÁjOláþ24 ¨N)`¦ìX íJºL^|¥ Å¥p{7l6;cB©·EáÑ¥DTÝ77ÃKa¤B&5<#° ³Ñzâ¶qÄ7wëõØ3XNV=àHë$LcòÜ2K°u$v6Lov÷f)ù½ ³ñ;*¸Âw5%Gõ]îר#¢ô IëßD¥ÙD(ǯþKsç8§X:& 3·# HJV%«wtKÔ9*/rð/dD.õ¼¾LåPÝ^üRG¾4sæÌ5;|³ýÍB9¼¦2H¼Må¡ WwWeH9 ݨX`8±­RÎüz~=F¤ã&g,Õ5·c²Î4AS)ñv¥Fô,´oÂ÷2­*oÍIx{uf Å·¼W[_$ôÊVøb|È=`ÓÈÈ&MïLTa3°vCdÝ®fçòµuFÝHlêh)9jÇUd9[T¸¹ZÄã9*SùÆvܼÚBp¸¸°E¿¡¤#êNííØTd0/Áª ` C­iÇÞ ¨V ³E !ø2¼ØBwKõ õ*#\õ­Lµ45VâEf§;BÌú5 $/âuÔºîºD~4[ÿ×ës>¼$¨TPúÀX£½R<=[|?ô,O>ëyKÉXçá|ù¡ ¹ å*hô0ÞBßâ[༠<:V¹ñ¦p ¡ZbáͶ(IXÈøÒC## Heading
Now I just want to create the pdf file with this content (get as report.content) and save on the server (In Report folder of the project).
jsreport server returned you pdf document in string. simply you have to write this string into file. if you are using php you can do it by
file_put_contents()
sample demo to represent what is returned from jsreport server
// Read the input pdf file in string
$stringPdf = file_get_contents("input.pdf");
echo $stringPdf;
// write string file in pdf
file_put_contents("output.pdf",$stringPdf);
?>

Awk space-delimited file content

I have a file whose lines I want to split using either space or "_".
Its format is
f 5.287102213 _10_ RTR --- 312 cbr 120 [13a a 6 800] ------- [6:0 20:0 29 20] [15] 1 0
s 5.288000000 _0_ AGT --- 322 cbr 100 [0 0 0 0] ------- [0:0 2:0 32 0] [18]
My awk script is as follows:
`#!/usr/bin/awk -f
BEGIN {FS="[[:space:]]|_"} # use posix space or underscore for FS
{
action = $1;
time = $2;
sta = $4 ; # shifted here because underscores are delimiters
dest = $6;
app = $10;
pkt_size = $11;
#print $1
#print $2
print $5
#print $4
#print $5
#print $6
#print $7
#print $8
#print $9
#print $10
if( action == "s" && dest == "MAC" && app == "cbr"){
startTime+=time ;
count++;
}
if( action == "r" && dest == "MAC" && app == "cbr"){
endTime+=time ;
receivedSize+=pkt_size ;
}
}`
As seen in the above script, from the above script I was expecting RTR to be in $4.
But I find that the output of $3 is as follows:
RTR --- 312 cbr 120 [13a a 6 800] ------- [6:0 20:0 29 20] [15] 1 0
AGT --- 322 cbr 100 [0 0 0 0] ------- [0:0 2:0 32 0] [18] 0 0
RTR --- 322 cbr 100 [0 0 0 0] ------- [0:0 2:0 32 0] [18] 0 0
What am I doing wrong? Am new to awk.
Change your FS value to [[:space:]_]+ to get the tokenization (splitting into fields) you want.
Test it with this statement to see the fields recognized:
awk -F'[[:space:]_]+' '{for(i=1;i<=NF;++i){print i ": " $i}}' \
<<<'f 5.287102213 _10_ RTR --- 312 cbr 120 [13a a 6 800] ------- [6:0 20:0 29 20] [15] 1 0'
The problem with your FS value, [[:space:]]|_, is that
it only recognizes 1 character at a time as the separator
it only recognizes either whitespace or _ as the separator.
Note that specifying an explicit FS value other than ' ' (a single space) causes awk to look for a single instance of that separator, and interprets multiple adjacent instances as separating multiple - and thus empty - fields.
Thus, in your case, the spans <space>_ and _<space> each represent not a single separator, but two separators abutting an empty field.
If you want spans (runs) of a given character or characters from a set to be interpreted as a single separator instance, use duplication symbol +.
However, the proposed FS value, [[:space:]_]+, may be too permissive, as it would recognize a run of any mix of whitespace and _ chars. as a separator.
To be more restrictive, you could use the following FS value:
[[:space:]]+_?|_?[[:space:]]+
That said, if the _ chars in your input function more like delimiters enclosing only one field, a better solution may be:
to use the DEFAULT value of FS, which recognizes runs of whitespace as delimiters
to strip the _ delimiters from field $3: gsub("^_|_$", "", $3)