code wiki / (root) / nx_lib_pdf_stream_diag.nx

nx_lib_pdf_stream_diag.nx source

↩ module page · 68 lines · 3154 B

1// nx_lib_pdf_stream_diag.nx -- dump a decompressed CONTENT stream from the FOP 2// PDF so its exact text-showing encoding (literal vs hex, 1- vs 2-byte, Tf font) 3// is visible. Ends the guessing about why extraction yields numbers. 4import "nx_syscalls.nx" 5import "nx_zlib_wrap.nx" 6const K_MAGIC_8388608: i64 = 8388608 7 8func sd_puts(s: *u8) -> i64 { var n: i64 = 0; while s[n] != (0 as u8) { n = n + 1 } sys_write(1, s, n); return 0 } 9func sd_wr(p: *u8, n: i64) -> i64 { sys_write(1, p, n); return 0 } 10func sd_putn(v: i64) -> i64 { 11 let bb: *u8 = sys_mmap(28); var m: i64 = v 12 let t: *u8 = sys_mmap(28); var k: i64 = 0 13 if m == 0 { t[0] = 48 as u8; k = 1 } 14 while m > 0 { t[k] = (48 + (m - (m/10)*10)) as u8; m = m / 10; k = k + 1 } 15 var i: i64 = 0; while i < k { bb[i] = t[k - 1 - i]; i = i + 1 } sys_write(1, bb, k); return 0 16} 17func sd_find(hay: *u8, hayn: i64, start: i64, needle: *u8, nlen: i64) -> i64 { 18 if hayn < nlen { return 0 - 1 } 19 var i: i64 = start 20 while i <= hayn - nlen { 21 var j: i64 = 0; var st: i64 = 0 22 while st == 0 { if j >= nlen { st = 2 } if st == 0 { if hay[i+j] != needle[j] { st = 1 } if st == 0 { j = j + 1 } } } 23 if st == 2 { return i } 24 i = i + 1 25 } 26 return 0 - 1 27} 28 29func main() -> i64 { 30 let lb: *i64 = sys_mmap(16) as *i64 31 let buf: *u8 = sys_read_file("knowledge/fetched/pmc_cd004504.pdf\x00" as *u8, lb) 32 if (buf as i64) == 0 { sd_puts("cannot read PDF\n"); return 1 } 33 let n: i64 = lb[0] 34 var pos: i64 = 0 35 var shown: i64 = 0 36 while shown < 2 { 37 let s: i64 = sd_find(buf, n, pos, "stream" as *u8, 6) 38 if s < 0 { shown = 2 } 39 else { 40 var ds: i64 = s + 6 41 if ds < n { if (buf[ds] as i64) == 0x0d { ds = ds + 1 } } 42 if ds < n { if (buf[ds] as i64) == 0x0a { ds = ds + 1 } } 43 let e: i64 = sd_find(buf, n, ds, "endstream" as *u8, 9) 44 if e < 0 { shown = 2 } 45 else { 46 let z: *NxZlibResult = nx_zlib_inflate(((buf as i64) + ds) as *u8, e - ds, K_MAGIC_8388608) 47 if (z as i64) != 0 { if z.error_code == NX_ZLIB_OK { 48 let dec: *u8 = z.output_data 49 let dlen: i64 = z.output_size 50 let bt: i64 = sd_find(dec, dlen, 0, "BT" as *u8, 2) 51 let hasTj: i64 = sd_find(dec, dlen, 0, "Tj" as *u8, 2) 52 let hasTJ: i64 = sd_find(dec, dlen, 0, "TJ" as *u8, 2) 53 let iscmap: i64 = sd_find(dec, dlen, 0, "begincmap" as *u8, 9) 54 if bt >= 0 { if iscmap < 0 { if hasTj >= 0 { if hasTJ >= 0 || hasTj >= 0 { 55 sd_puts("=== CONTENT STREAM dlen="); sd_putn(dlen); sd_puts(" (dump from first BT) ===\n") 56 var st2: i64 = bt 57 var w: i64 = 800; if st2 + w > dlen { w = dlen - st2 } 58 sd_wr(((dec as i64) + st2) as *u8, w) 59 sd_puts("\n=== end stream ===\n") 60 shown = shown + 1 61 } } } } 62 } } 63 pos = e + 9 64 } 65 } 66 } 67 return 0 68}