This is an automated email from the ASF dual-hosted git repository.

leginee pushed a commit to branch backport/pdfimport-pdfbox
in repository https://gitbox.apache.org/repos/asf/openoffice.git

commit fe88bb8ae28be492f92c01fd303d99aa958d8660
Author: Peter <[email protected]>
AuthorDate: Tue Sep 8 23:27:41 2026 +0200

    sdext: add an Apache-licensed PDF import backend and a backend seam
    
    Backport of the source half of the PDFBox PDF import work, which is running 
on
    the Bazel branch.  Source only: this compiles nothing new on trunk yet, and 
the
    dmake wiring is deliberately not included -- see below.
    
    PDF import has never worked on Windows.  The only backend, xpdfimport, links
    poppler (GPLv2), which may not be linked into an Apache-licensed 
soffice.bin,
    so configure.ac gates the whole extension off by default and no stock build 
has
    ever shipped it.  Rather than modernise against poppler -- whose API this 
code
    has drifted about ten years behind, and whose licence keeps the result
    unshippable -- the backend becomes pluggable and a second one is added that 
is
    Apache-2.0.
    
    The seam is a process boundary and a wire protocol, not a C++ interface:
    pdfimport.uno.dll links no engine's headers, libraries or licence.  A PDF is
    untrusted input, and a fault in the parser should cost one document rather 
than
    the session.  PROTOCOL.md is that contract, written down for the first time.
    
    Two defects this avoids that the poppler backend has: it sends
    getTransformedFontSize(), which already includes Tm's scale, alongside the 
raw
    Tm, so a document with its scale in Tm is scaled twice; and it emits 
hyperlink
    rectangles in points where the consumer stores page coordinates in 1/7200 
inch,
    100x too small to contain any text.
    
    Still required before this builds or runs under dmake:
      - wrapper/makefile.mk: pdfbackend.obj is not in any SLOFILES list;
      - a build for pdfboxwrapper, and a way to obtain the four PDFBox 3.0.8 
jars
        (pdfbox, pdfbox-io, fontbox, commons-logging) -- trunk has no mechanism 
to
        fetch them;
      - configure.ac: --enable-pdfimport still also demands 
--with-system-poppler;
      - packaging: the jar has to land where pdfbackend.cxx probes.
    
    The type change in filter/.../pdf_Portable_Document_Format.xcu is the one 
hunk
    that is only correct once the above lands: it names a detect service and
    preferred filter that do not exist until the extension is built.
    
    Co-Authored-By: Claude Opus 5 <[email protected]>
    Claude-Session: https://claude.ai/code/session_01CH5PJJyJfirMStqJEZTxBD
---
 .../types/pdf_Portable_Document_Format.xcu         |   13 +-
 main/sdext/source/pdfimport/PROTOCOL.md            |  299 ++++++
 main/sdext/source/pdfimport/inc/pdfbackend.hxx     |   99 ++
 .../src/org/apache/openoffice/pdfimport/Main.java  |  171 +++
 .../apache/openoffice/pdfimport/PdfiEngine.java    | 1113 ++++++++++++++++++++
 .../apache/openoffice/pdfimport/PdfiWriter.java    |  190 ++++
 main/sdext/source/pdfimport/pdfimport.component    |   53 +
 main/sdext/source/pdfimport/wrapper/pdfbackend.cxx |  330 ++++++
 main/sdext/source/pdfimport/wrapper/wrapper.cxx    |  127 ++-
 9 files changed, 2352 insertions(+), 43 deletions(-)

diff --git 
a/main/filter/source/config/fragments/types/pdf_Portable_Document_Format.xcu 
b/main/filter/source/config/fragments/types/pdf_Portable_Document_Format.xcu
index 3291e0c3ad..a9966db8f6 100644
--- a/main/filter/source/config/fragments/types/pdf_Portable_Document_Format.xcu
+++ b/main/filter/source/config/fragments/types/pdf_Portable_Document_Format.xcu
@@ -20,12 +20,19 @@
  ***********************************************************-->
 
        <node oor:name="pdf_Portable_Document_Format" oor:op="replace" >
-               <prop oor:name="DetectService"/>
+               <!-- PDF import is built in rather than shipped as an 
extension, so the
+                    type carries its detect service and preferred import 
filter here.
+                    This one fragment is pulled into six module registries 
(calc, draw,
+                    impress, math, web, writer); leaving it empty and 
declaring the type
+                    a second time from sdext instead would make the winner 
depend on the
+                    order configmgr happens to read share/registry, since both 
use
+                    oor:op="replace". -->
+               <prop 
oor:name="DetectService"><value>com.sun.star.comp.documents.PDFDetector</value></prop>
                <prop oor:name="URLPattern"/>
                <prop oor:name="Extensions"><value>pdf</value></prop>
                <prop oor:name="MediaType"><value>application/pdf</value></prop>
-               <prop oor:name="Preferred"><value>false</value></prop>
-               <prop oor:name="PreferredFilter"/>
+               <prop oor:name="Preferred"><value>true</value></prop>
+               <prop 
oor:name="PreferredFilter"><value>draw_pdf_import</value></prop>
                <prop oor:name="UIName">
                        <value>PDF - Portable Document Format</value>
                </prop>
diff --git a/main/sdext/source/pdfimport/PROTOCOL.md 
b/main/sdext/source/pdfimport/PROTOCOL.md
new file mode 100644
index 0000000000..f58969c150
--- /dev/null
+++ b/main/sdext/source/pdfimport/PROTOCOL.md
@@ -0,0 +1,299 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements.  See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership.  The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License.  You may obtain a copy of the License at
+
+   http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied.  See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+# The pdfi helper protocol
+
+`pdfimport.uno.dll` does not parse PDF itself.  It spawns a **helper process**,
+feeds it a file name, and reads back a stream of drawing commands which it
+replays into `pdfi::ContentSink` (`inc/contentsink.hxx`).  Everything above the
+sink — the document tree in `tree/`, the ODF emitters in `odf/` and `sax/` — is
+backend-agnostic and never sees a PDF.
+
+This file is the contract.  Anything that implements it is a usable backend;
+see `inc/pdfbackend.hxx` for how one is selected at run time.
+
+## Why a separate process
+
+Originally: a licence firewall.  The only backend was `xpdfimport`, which links
+poppler (GPLv2) and therefore may not be linked into an Apache-licensed
+`soffice.bin`.
+
+It is kept for a better reason.  A PDF is untrusted input and the parsing code
+is where the memory-safety defects live; a crash or a corrupted heap in the
+helper costs one document, not the user's session.  The split is now a
+containment boundary, not a workaround, and new backends keep it even when
+their licence would permit linking.
+
+## Invocation
+
+    <program> [prefix args...] [-f <binary-file>] <pdf-system-path>
+
+* The PDF path is a **native system path**, not a file URL, and is always last.
+* `-f <path>` redirects the binary channel (v1 only, see below).
+* `-opw <pw>` / `-upw <pw>` supply owner / user passwords on the command line.
+  Prefer stdin; these exist because `xpdfimport` accepted them.
+
+**stdin** — the helper reads exactly one line before anything else: the open
+password, possibly empty.  It must tolerate EOF.  The password is *always*
+written by the caller, so a helper that does not read it will make the caller
+block on a full pipe.
+
+**exit status** — `0` on success.  Any other value, or a helper that dies, is
+reported to the user as a failed import.
+
+## Framing
+
+Two framings exist.  A backend declares which it speaks; the caller adapts.
+
+**v1 — `BINARY_ON_STDERR`** (`xpdfimport`).  Text commands on stdout, binary
+payloads on stderr.  Both processes must touch the same pipe at the same time
+or they deadlock, so the helper has to flush one stream before writing to the
+other.  This is the framing described by the `SYNC STREAMS` comment in
+`xpdfwrapper/pdfioutdev_gpl.cxx`; it exists only because that helper already
+used stderr for binary before anyone needed stderr for anything else.
+
+**v2 — `BINARY_INLINE`** (everything new).  One stream.  A binary payload
+follows immediately after the newline of the command line that announced its
+length, then the next command line follows immediately after the payload's last
+byte.  No second pipe, no flush discipline, nothing to deadlock — and **stderr
+is left free for diagnostics**, which matters for any helper on a runtime that
+writes to stderr on its own account (a JVM emits warnings and stack traces
+there and cannot be reliably stopped from doing so).
+
+A payload's length is always stated on the line before it, so v1 and v2 differ
+only in *which handle* the reader takes those bytes from.
+
+## Coordinate spaces and units
+
+This is the part of the contract that is easiest to get wrong, because the
+protocol is deliberately **not** in a single space: the consumer transforms 
some
+values and uses others as they arrive.  Both of the geometry bugs found while
+bringing up the PDFBox backend were violations of this section, and neither
+looked like a geometry bug from the outside -- one made all text invisible
+rather than misplaced.
+
+**Device space** is 1/7200 inch (`PDFI_OUTDEV_RESOLUTION`, 
`inc/pdfihelper.hxx`),
+y **down**, origin at the top-left of the cropped and rotated page.  A PDF 
point
+is 1/72 inch, so one point is exactly **100 device units**.
+
+**User space** is PDF default user space for the page: points, y **up**, origin
+at the crop box's lower-left corner.
+
+| Value | Space | Why |
+| --- | --- | --- |
+| path points, clip paths | user | `pdfiprocessor.cxx` multiplies them by the 
declared CTM |
+| **glyph rectangles** (`drawChar`) | user | same -- `drawCharGlyphs` calls 
`calcTransformedRectBounds` with the CTM |
+| hyperlink rectangles (`drawLink`) | device | stored as page coordinates 
unchanged |
+| page size (`startPage`) | device | used as the page extent directly |
+| font size (`updateFont`) | device | `drawtreevisiting.cxx` converts back 
with `size*72/7200` |
+| font matrix (`drawChar`) | none -- normalised | applied about the glyph 
origin, *in addition* to the font size |
+| declared CTM (`updateCtm`) | user to device | see below |
+
+### The declared CTM
+
+`updateCtm` declares the transform the consumer applies to path and glyph
+coordinates.  What it should contain depends on what your engine already did:
+
+* If the engine reports path points with the content stream's own CTM **already
+  applied** -- PDFBox's `PDFGraphicsStreamEngine` does -- then declare the page
+  transform alone, and `q`/`Q` never has to be tracked.
+* If the engine reports raw operands -- poppler's `GfxPath` does -- then 
declare
+  the page transform composed with the current content CTM.
+
+Either way the product reaching the consumer is the same.  Images are the
+exception: `drawImage` places the unit square, so its CTM is always the page
+transform composed with the image's own matrix.
+
+### The page transform
+
+With crop box `(x0,y0)-(x1,y1)` in points, `S = 100`, and `/Rotate` normalised 
to
+0/90/180/270, as `(a,b,c,d,e,f)` mapping `(x,y)` to `(ax+cy+e, bx+dy+f)`:
+
+    0     ( S,  0,  0, -S,  -S*x0,  S*y1 )
+    90    ( 0,  S,  S,  0,  -S*y0, -S*x0 )
+    180   (-S,  0,  0,  S,   S*x1, -S*y0 )
+    270   ( 0, -S, -S,  0,   S*y1,  S*x1 )
+
+Page size is `(x1-x0)*S` by `(y1-y0)*S`, swapped for 90 and 270.
+
+`/Rotate` belongs **here**, not left to the consumer.  Do not assume a library
+applies it: PDFBox does not, and a page processed at 0, 90 and 270 yields
+byte-identical coordinates, so this fails silently and every landscape or
+scanned document imports sideways.
+
+### The font matrix
+
+Send the text matrix divided by its own vertical scale, so that its vertical
+scale becomes unity.  It carries orientation, shear and the horizontal/vertical
+aspect ratio, and **no overall scale**.
+
+The consumer applies it as a transform about each glyph's origin *and*
+separately sizes the text from `updateFont`.  Sending a matrix that still
+carries the type scale therefore applies that scale twice.  Documents that put
+their scale in `Tm` with `Tf 1` are common, and poppler gets this wrong -- it
+sends `getTransformedFontSize()`, which already includes `Tm`'s scale, next to
+the raw `Tm`.
+
+### Image encodings
+
+`PNG`, `JPEG`, `PBM` and `PPM` are all accepted, and a backend should send
+whichever the image already is rather than normalising to one.  Re-encoding a
+lossy image losslessly is the expensive mistake: it is bit-exact about content
+that was never crisp, and it multiplied one photographic document by three.
+Send the stored bytes unchanged when they are already a usable JPEG, stay lossy
+when the source was lossy, and keep PNG for anything stored losslessly.
+
+### Capturing a stream for inspection
+
+The stream is binary.  Redirect it with a shell that will not transcode:
+PowerShell's `>` re-encodes as UTF-8 with a BOM and rewrites LF as CRLF, which
+silently inflates every payload and makes a correct backend look like it has
+regressed.  Use `bash` redirection, or have the helper write the file itself.
+
+### Numbers
+
+C locale, `printf` `%f`, always a dot.  A helper that emits `1,5` for `1.5` has
+its coordinates read as `1.0` by `rtl::OString::toDouble` and silently 
displaces
+the whole page.
+
+### Worked example
+
+A4 landscape, crop box `(0,0)-(794,595)`, `/Rotate 0`, 14pt text with `Tm` the
+identity whose first glyph sits at user `(39.7, 40.2)`:
+
+    startPage 79400 59500                     794*100 by 595*100
+    updateCtm 100 0 0 -100 0 59500            S, 0, 0, -S, -S*x0, S*y1
+    updateFont <id> 1 0 0 0 1400 0 <name>     14pt * 100
+    drawChar 39.7 <top> <right> <bottom> 1 0 0 1 T
+
+Note the two orders of magnitude between `updateCtm`/`updateFont` and
+`drawChar`: that contrast is the check.  Glyph coordinates in the tens of
+thousands mean device space has leaked into a user-space field, and the symptom
+is text frames metres wide translated far off the canvas -- invisible, not
+merely misplaced.
+
+## Grammar
+
+One command per line, tokens separated by single spaces, `\n`-terminated.
+Numbers are C `printf` `%d` / `%f` / `%lld` in the **C locale** — a helper that
+formats `1,5` for `1.5` will silently produce a corrupt document.
+
+Two commands (`drawChar`, `updateFont`) end in a free-text field that consumes
+the rest of the line; in those, `\n`, `\r` and `\` are escaped as `\n`, `\r`,
+`\`.  Text is UTF-8.
+
+### Document and page
+
+| Command | Arguments |
+| --- | --- |
+| `setPageNum` | `<int nPages>` — total page count, sent once, before any page 
|
+| `startPage` | `<double width> <double height>` |
+| `endPage` | — |
+
+### Graphics state
+
+| Command | Arguments |
+| --- | --- |
+| `saveState` / `restoreState` | — |
+| `updateCtm` | `<a> <b> <c> <d> <e> <f>` — PDF matrix order |
+| `updateFillColor` / `updateStrokeColor` | `<r> <g> <b> <a>`, each 0..1 |
+| `updateLineWidth` | `<double>` |
+| `updateLineCap` | `0` butt, `1` round, `2` square |
+| `updateLineJoin` | `0` miter, `1` round, `2` bevel |
+| `updateMiterLimit` | `<double>` |
+| `updateFlatness` | `<int>` |
+| `updateLineDash` | *(empty = solid)*, else `<phase> <n> <d1> … <dn>` |
+| `setTextRenderMode` | `<int>` — PDF Tr operator |
+
+### Paths
+
+`strokePath`, `fillPath`, `eoFillPath`, `clipPath`, `eoClipPath` all take the
+same trailing path description:
+
+    subpath <int closed> <x> <y> <int isControlPoint> ... [subpath ...]
+
+Points with `isControlPoint = 1` come in pairs and, with the following ordinary
+point, form one cubic Bézier segment.
+
+`fillPath` and `eoFillPath` are additionally stroked by the caller when the
+filled area is very small, so hairline table rules survive.
+
+### Text
+
+| Command | Arguments |
+| --- | --- |
+| `updateFont` | `<int64 id> <int embedded> <int bold> <int italic> <int 
underline> <double size> <int fileLen> <name…>` |
+| `drawChar` | `<x1> <y1> <x2> <y2> <m00> <m01> <m10> <m11> <text…>` |
+| `endTextObject` | — |
+
+`updateFont` assigns a **stable numeric id** to a font; the caller caches it, 
so
+the same id must not be re-described with a different `fileLen`.  If `fileLen`
+is non-zero, that many bytes of the embedded font file follow on the binary
+channel and the caller runs them through `com.sun.star.awt.FontIdentificator`
+to recover the real family name.  Send `0` and a good name if the font is not
+embedded.
+
+### Images
+
+    drawImage           <w> <h> <maskColors> <image>
+    drawMask            <w> <h> <invert>     <image>
+    drawMaskedImage     <w> <h> <mw> <mh> <invert> <image> <mask>
+    drawSoftMaskedImage <w> <h> <mw> <mh>    <image> <mask>
+
+where each `<image>` is the two tokens
+
+    <format> <byteCount>
+
+with `<format>` one of `PNG`, `JPEG`, `PBM`, `PPM`.  The payloads follow, in 
the
+order the tokens appeared, after the end of the line.  For `drawImage` a
+non-zero `maskColors` means a further `maskColors` bytes follow the image
+payload: the first half are per-component minima, the second half maxima.
+
+### Links
+
+    drawLink <x1> <y1> <x2> <y2> <uri…>
+
+## Writing a backend
+
+Implement the grammar **and the coordinate section above**, pick v2, and add 
one
+entry to the candidate table in `wrapper/pdfbackend.cxx`.  Nothing above
+`ContentSink` changes, and nothing links against your engine: the abstraction
+here is the process boundary, not a C++ interface, which is what keeps
+`pdfimport.uno.dll` free of every engine's headers, libraries and licence.
+
+The grammar is the easy half.  Everything that went wrong bringing up the first
+non-poppler backend was semantic -- right tokens, wrong space -- so before
+trusting a new helper, check it against the invariants that hold for any
+backend:
+
+* page size equals crop-box points times 100, with width and height swapped for
+  `/Rotate` 90 and 270;
+* every path and glyph coordinate falls inside the crop box (they are user
+  space, so they are bounded by it);
+* the font matrix has vertical scale 1;
+* every announced payload length is consumed exactly, and the stream ends
+  cleanly;
+* no number contains a comma.
+
+`PDFI_BACKEND` pins one engine and fails rather than falling through to 
another,
+so the same document can be run through two backends and the output compared.
+
+Set `PDFI_BACKEND` in the bootstrap environment to force a specific one —
+`PDFI_BACKEND=xpdf` pins the legacy helper, which is how two backends are
+compared on the same document.
diff --git a/main/sdext/source/pdfimport/inc/pdfbackend.hxx 
b/main/sdext/source/pdfimport/inc/pdfbackend.hxx
new file mode 100644
index 0000000000..8b1c511412
--- /dev/null
+++ b/main/sdext/source/pdfimport/inc/pdfbackend.hxx
@@ -0,0 +1,99 @@
+/**************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************/
+
+#ifndef INCLUDED_PDFI_PDFBACKEND_HXX
+#define INCLUDED_PDFI_PDFBACKEND_HXX
+
+#include "rtl/ustring.hxx"
+
+#include <vector>
+
+namespace com { namespace sun { namespace star {
+    namespace uno { class XComponentContext; template <typename> class 
Reference; }
+} } }
+
+namespace pdfi
+{
+    /** Which handle a helper delivers binary payloads (embedded fonts,
+        bitmaps) on.
+
+        Only the framing differs between these; the token grammar is
+        identical.  See PROTOCOL.md.
+     */
+    enum BinaryChannel
+    {
+        /** v1: text on stdout, binary on stderr.  The two processes must
+            alternate between the pipes in lockstep or they deadlock, and
+            stderr cannot be used for anything else.  Legacy xpdfimport only.
+         */
+        BINARY_ON_STDERR,
+
+        /** v2: one stream.  Each payload follows the newline of the line that
+            announced its length.  No flush discipline, and stderr stays free
+            for diagnostics -- required for any helper whose runtime writes
+            there on its own account.
+         */
+        BINARY_INLINE
+    };
+
+    /** A PDF parsing helper: what to spawn, and how it talks back.
+
+        Everything backend-specific lives here.  Adding an engine means adding
+        one of these to the table in pdfbackend.cxx -- no caller changes, and
+        nothing above ContentSink is aware that there is a choice at all.
+     */
+    struct PdfBackend
+    {
+        /** Stable identifier, also what PDFI_BACKEND matches against. */
+        rtl::OUString                   aId;
+
+        /** File URL of the program to spawn -- or a bare name, which is
+            resolved against PATH.  Empty means unavailable.
+         */
+        rtl::OUString                   aProgram;
+
+        /** Arguments that precede the PDF path (e.g. -jar <helper>.jar). */
+        std::vector< rtl::OUString >    aPrefixArgs;
+
+        BinaryChannel                   eBinaryChannel;
+
+        PdfBackend() : eBinaryChannel( BINARY_ON_STDERR ) {}
+
+        bool isAvailable() const { return aProgram.getLength() != 0; }
+    };
+
+    /** Pick the backend to run.
+
+        Candidates are tried in preference order and the first one whose
+        program is actually present on disk wins, so a build that ships only
+        some of them needs no configuration.  Setting the bootstrap variable
+        PDFI_BACKEND to an id restricts the search to that one backend --
+        which is how a document is rendered through two engines for
+        comparison, and how a test pins the engine it is asserting against.
+
+        @return a backend with isAvailable() false if none was found.
+     */
+    PdfBackend selectPdfBackend(
+        const com::sun::star::uno::Reference<
+              com::sun::star::uno::XComponentContext >& xContext );
+}
+
+#endif /* INCLUDED_PDFI_PDFBACKEND_HXX */
diff --git 
a/main/sdext/source/pdfimport/pdfboxwrapper/src/org/apache/openoffice/pdfimport/Main.java
 
b/main/sdext/source/pdfimport/pdfboxwrapper/src/org/apache/openoffice/pdfimport/Main.java
new file mode 100644
index 0000000000..4dfe4980bf
--- /dev/null
+++ 
b/main/sdext/source/pdfimport/pdfboxwrapper/src/org/apache/openoffice/pdfimport/Main.java
@@ -0,0 +1,171 @@
+/**************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************/
+
+package org.apache.openoffice.pdfimport;
+
+import org.apache.pdfbox.Loader;
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.PDPage;
+import org.apache.pdfbox.pdmodel.font.PDFont;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * The PDFBox pdfi backend: reads a PDF, writes the pdfi helper protocol on
+ * stdout.  See PROTOCOL.md for the contract this implements and
+ * wrapper/pdfbackend.cxx for how it gets selected.
+ *
+ * <p>Invoked as {@code java -jar pdfimport-pdfbox.jar [-opw pw] [-upw pw]
+ * [-f file] <pdf-path>}, with the open password as the first line of stdin.
+ * The {@code -f} option is accepted and ignored: it redirects the binary
+ * channel of the v1 framing, and this backend speaks v2, where payloads travel
+ * inline on stdout and there is no separate channel to redirect.</p>
+ */
+public final class Main
+{
+    private Main() {}
+
+    public static void main( String[] args )
+    {
+        String aOwnerPassword = null;
+        String aUserPassword = null;
+        String aPath = null;
+
+        for( int i = 0; i < args.length; ++i )
+        {
+            final String a = args[i];
+            if( "-opw".equals( a ) && i + 1 < args.length )
+                aOwnerPassword = args[++i];
+            else if( "-upw".equals( a ) && i + 1 < args.length )
+                aUserPassword = args[++i];
+            else if( "-f".equals( a ) && i + 1 < args.length )
+                ++i; // v1 binary redirect; not applicable to v2
+            else
+                aPath = a; // the PDF path is always last
+        }
+
+        // The caller always writes the password line, so it must always be
+        // read: leaving it in the pipe risks blocking the caller on a full
+        // buffer for a large document.
+        final String aStdinPassword = readPasswordLine();
+
+        if( aPath == null )
+        {
+            System.err.println( "pdfimport-pdfbox: no input file given" );
+            System.exit( 1 );
+        }
+
+        String aPassword = aStdinPassword;
+        if( aPassword == null || aPassword.length() == 0 )
+            aPassword = aOwnerPassword != null ? aOwnerPassword : 
aUserPassword;
+        if( aPassword == null )
+            aPassword = "";
+
+        PDDocument aDoc = null;
+        try
+        {
+            aDoc = Loader.loadPDF( new File( aPath ), aPassword );
+            convert( aDoc );
+        }
+        catch( Throwable e )
+        {
+            // stderr is free in v2 framing, so a failure can actually say why.
+            System.err.println( "pdfimport-pdfbox: " + e );
+            e.printStackTrace();
+            System.exit( 1 );
+        }
+        finally
+        {
+            if( aDoc != null )
+            {
+                try
+                {
+                    aDoc.close();
+                }
+                catch( Exception e )
+                {
+                    // nothing useful left to do at this point
+                }
+            }
+        }
+    }
+
+    private static void convert( PDDocument aDoc ) throws Exception
+    {
+        final PdfiWriter aOut = new PdfiWriter();
+
+        final int nPages = aDoc.getNumberOfPages();
+
+        // Sent before any page: the consumer sizes its progress bar with it.
+        aOut.cmd( "setPageNum" ).i( nPages ).eol();
+
+        // Font identity spans the document -- the consumer caches attributes 
by
+        // id and expects an id to keep meaning the same font across pages.
+        final Map<PDFont, Long> aFontIds = new HashMap<PDFont, Long>();
+        final long[] pNextFontId = new long[] { 1 };
+
+        for( int i = 0; i < nPages; ++i )
+        {
+            final PDPage aPage = aDoc.getPage( i );
+            try
+            {
+                new PdfiEngine( aPage, aOut, aFontIds, pNextFontId ).run();
+            }
+            catch( Exception e )
+            {
+                // One unparsable page should not cost the other 200.
+                System.err.println( "pdfimport-pdfbox: page " + ( i + 1 )
+                                    + " failed: " + e );
+            }
+        }
+
+        aOut.finish();
+    }
+
+    /**
+     * Reads the open password: one line, ISO-8859-1, as written by
+     * wrapper.cxx.  An immediate EOF means no password, which is the normal
+     * case.
+     */
+    private static String readPasswordLine()
+    {
+        try
+        {
+            final InputStream aIn = System.in;
+            final ByteArrayOutputStream aBuf = new ByteArrayOutputStream( 128 
);
+            int c;
+            while( ( c = aIn.read() ) != -1 && c != '\n' )
+            {
+                if( c != '\r' )
+                    aBuf.write( c );
+            }
+            return new String( aBuf.toByteArray(), "ISO-8859-1" );
+        }
+        catch( Exception e )
+        {
+            return "";
+        }
+    }
+}
diff --git 
a/main/sdext/source/pdfimport/pdfboxwrapper/src/org/apache/openoffice/pdfimport/PdfiEngine.java
 
b/main/sdext/source/pdfimport/pdfboxwrapper/src/org/apache/openoffice/pdfimport/PdfiEngine.java
new file mode 100644
index 0000000000..c401c776e3
--- /dev/null
+++ 
b/main/sdext/source/pdfimport/pdfboxwrapper/src/org/apache/openoffice/pdfimport/PdfiEngine.java
@@ -0,0 +1,1113 @@
+/**************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************/
+
+package org.apache.openoffice.pdfimport;
+
+import org.apache.pdfbox.contentstream.PDFGraphicsStreamEngine;
+import org.apache.pdfbox.cos.COSName;
+import org.apache.pdfbox.pdmodel.PDPage;
+import org.apache.pdfbox.pdmodel.common.PDRectangle;
+import org.apache.pdfbox.pdmodel.font.PDFont;
+import org.apache.pdfbox.pdmodel.font.PDFontDescriptor;
+import org.apache.pdfbox.pdmodel.graphics.PDLineDashPattern;
+import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
+import org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace;
+import org.apache.pdfbox.pdmodel.graphics.image.PDImage;
+import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
+import org.apache.pdfbox.pdmodel.graphics.state.PDGraphicsState;
+import org.apache.pdfbox.pdmodel.graphics.state.PDTextState;
+import org.apache.pdfbox.pdmodel.interactive.action.PDAction;
+import org.apache.pdfbox.pdmodel.interactive.action.PDActionURI;
+import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
+import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink;
+import org.apache.pdfbox.util.Matrix;
+import org.apache.pdfbox.util.Vector;
+
+import javax.imageio.IIOImage;
+import javax.imageio.ImageIO;
+import javax.imageio.ImageWriteParam;
+import javax.imageio.ImageWriter;
+import javax.imageio.stream.ImageOutputStream;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Area;
+import java.awt.geom.GeneralPath;
+import java.awt.geom.Path2D;
+import java.awt.geom.PathIterator;
+import java.awt.geom.Point2D;
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Walks one page's content stream and emits the pdfi helper protocol.
+ *
+ * <h3>Coordinate spaces -- read this before changing any geometry</h3>
+ *
+ * The protocol is not in one space, and that is not an accident: it mirrors
+ * what the consumer in tree/pdfiprocessor.cxx does with each kind of value.
+ *
+ * <ul>
+ * <li><b>Paths</b> go out in PDF <em>user</em> space, untransformed, because
+ *     pdfiprocessor.cxx:674 multiplies them by the declared CTM itself.
+ *     PDFBox has already applied the content stream's own CTM to the points
+ *     it hands us, so the CTM we declare is just the page's user-to-device
+ *     transform -- which is why this class never has to track q/Q.</li>
+ * <li><b>Glyph rectangles</b> go out in <em>device</em> space, already
+ *     transformed, because the consumer uses them as-is.</li>
+ * <li><b>Images</b> declare a CTM of user-to-device composed with the image's
+ *     own matrix, since the consumer places an image by transforming the unit
+ *     square.</li>
+ * <li><b>The font matrix</b> is the raw text matrix (Tm), carrying no page
+ *     transform at all -- it tells the consumer how the text is oriented and
+ *     sheared, nothing more.</li>
+ * </ul>
+ *
+ * Device space is 1/7200 inch, y down, origin at the top left of the cropped
+ * and rotated page.
+ *
+ * <h3>State</h3>
+ *
+ * Rather than mirroring the PDF graphics state machine, every drawing
+ * operation is wrapped in {@code saveState} / {@code restoreState} and states
+ * its own absolute state in between.  More verbose on the wire, but it cannot
+ * drift out of step with the document, and it makes clipping correct for free:
+ * the clip is redeclared per operation and unwound by {@code restoreState}.
+ */
+final class PdfiEngine extends PDFGraphicsStreamEngine
+{
+    private final PdfiWriter m_aOut;
+
+    /** PDF user space to consumer device space, including crop and /Rotate. */
+    private final AffineTransform m_aDevXform;
+
+    /** The declared CTM as a protocol argument list: user-to-device. */
+    private final double[] m_aDevCtm;
+
+    /** Page bounds in user space, for suppressing no-op clips. */
+    private final PDRectangle m_aCropBox;
+
+    private final Map<PDFont, Long> m_aFontIds;
+    private final long[] m_pNextFontId;
+
+    /** Subpaths of the path being built, in user space. */
+    private final List<SubPath> m_aPath = new ArrayList<SubPath>();
+    private SubPath m_aCurrent;
+    private Point2D m_aCurrentPoint = new Point2D.Double( 0, 0 );
+
+    /** Winding rule recorded by W/W*, applied when the path op arrives. */
+    private int m_nPendingClip = -1;
+
+    /** Whether a text run is open and still needs its endTextObject. */
+    private boolean m_bInText = false;
+
+    // Emitted-state cache.  The protocol is absolute, so a value only has to
+    // be restated when it actually changes; without this a text-heavy page
+    // costs a few hundred bytes per glyph, which on a long document is tens
+    // of megabytes down a pipe.
+    private double[] m_aLastCtm = null;
+    private double[] m_aLastFill = null;
+    private double[] m_aLastStroke = null;
+    private double m_fLastLineWidth = Double.NaN;
+    private int m_nLastLineCap = -1;
+    private int m_nLastLineJoin = -1;
+    private double m_fLastMiterLimit = Double.NaN;
+    private String m_aLastDash = null;
+    private long m_nLastFontId = -1;
+    private double m_fLastFontSize = Double.NaN;
+    private int m_nLastRenderMode = -1;
+
+    /** The clip currently declared, and whether a bracket is open for it. */
+    private Area m_aActiveClip = null;
+    private boolean m_bClipBracketOpen = false;
+
+    private static final class SubPath
+    {
+        final List<double[]> aPoints = new ArrayList<double[]>();
+        boolean bClosed = false;
+    }
+
+    PdfiEngine( PDPage aPage, PdfiWriter aOut,
+                Map<PDFont, Long> aFontIds, long[] pNextFontId )
+    {
+        super( aPage );
+        m_aOut = aOut;
+        m_aFontIds = aFontIds;
+        m_pNextFontId = pNextFontId;
+        m_aCropBox = aPage.getCropBox();
+        m_aDevXform = deviceTransform( m_aCropBox, aPage.getRotation() );
+        m_aDevCtm = new double[] {
+            m_aDevXform.getScaleX(), m_aDevXform.getShearY(),
+            m_aDevXform.getShearX(), m_aDevXform.getScaleY(),
+            m_aDevXform.getTranslateX(), m_aDevXform.getTranslateY() };
+    }
+
+    // ---- page geometry ----------------------------------------------------
+
+    /**
+     * Builds the user-to-device transform for a page.
+     *
+     * <p>PDFBox does <em>not</em> apply /Rotate -- measured, not assumed: a
+     * page processed with rotation 0, 90 and 270 yields byte-identical
+     * coordinates.  So the rotation has to be baked in here, or every
+     * landscape and scanned document imports sideways.</p>
+     */
+    static AffineTransform deviceTransform( PDRectangle aCrop, int nRotation )
+    {
+        final double S = PdfiWriter.DEVICE_UNITS_PER_POINT;
+        final double x0 = aCrop.getLowerLeftX(), y0 = aCrop.getLowerLeftY();
+        final double x1 = aCrop.getUpperRightX(), y1 = aCrop.getUpperRightY();
+
+        // normalise to 0/90/180/270; /Rotate may be negative or over 360
+        int r = nRotation % 360;
+        if( r < 0 )
+            r += 360;
+        r = ( r / 90 ) * 90;
+
+        // AffineTransform(m00, m10, m01, m11, m02, m12), i.e. a, b, c, d, e, f
+        switch( r )
+        {
+            case 90:
+                return new AffineTransform( 0, S, S, 0, -S * y0, -S * x0 );
+            case 180:
+                return new AffineTransform( -S, 0, 0, S, S * x1, -S * y0 );
+            case 270:
+                return new AffineTransform( 0, -S, -S, 0, S * y1, S * x1 );
+            default:
+                return new AffineTransform( S, 0, 0, -S, -S * x0, S * y1 );
+        }
+    }
+
+    /** Page size in device units, after crop and rotation. */
+    static double[] pageSize( PDRectangle aCrop, int nRotation )
+    {
+        final double S = PdfiWriter.DEVICE_UNITS_PER_POINT;
+        final double w = aCrop.getWidth() * S, h = aCrop.getHeight() * S;
+
+        int r = nRotation % 360;
+        if( r < 0 )
+            r += 360;
+        return ( ( r / 90 ) % 2 != 0 ) ? new double[] { h, w }
+                                       : new double[] { w, h };
+    }
+
+    // ---- page driver ------------------------------------------------------
+
+    void run() throws IOException
+    {
+        final double[] aSize = pageSize( m_aCropBox, getPage().getRotation() );
+        m_aOut.cmd( "startPage" ).d( aSize[0] ).d( aSize[1] ).eol();
+
+        processPage( getPage() );
+
+        endTextRun();
+        closeClipBracket();
+        emitLinks();
+
+        m_aOut.cmd( "endPage" ).eol();
+    }
+
+    private void emitLinks() throws IOException
+    {
+        final List<PDAnnotation> aAnnots;
+        try
+        {
+            aAnnots = getPage().getAnnotations();
+        }
+        catch( IOException e )
+        {
+            return; // a broken annotation array costs the links, not the page
+        }
+
+        for( PDAnnotation aAnnot : aAnnots )
+        {
+            if( !( aAnnot instanceof PDAnnotationLink ) )
+                continue;
+
+            final PDAction aAction = ( (PDAnnotationLink) aAnnot ).getAction();
+            if( !( aAction instanceof PDActionURI ) )
+                continue;
+
+            final String aURI = ( (PDActionURI) aAction ).getURI();
+            if( aURI == null || aURI.length() == 0 )
+                continue;
+
+            final PDRectangle aRect = aAnnot.getRectangle();
+            if( aRect == null )
+                continue;
+
+            // Annotation rectangles are in user space; the consumer stores
+            // hyperlink bounds as page coordinates, so they need the same
+            // device transform as everything else.
+            final Point2D a = toDevice( aRect.getLowerLeftX(), 
aRect.getLowerLeftY() );
+            final Point2D b = toDevice( aRect.getUpperRightX(), 
aRect.getUpperRightY() );
+
+            m_aOut.cmd( "drawLink" )
+                  .d( Math.min( a.getX(), b.getX() ) )
+                  .d( Math.min( a.getY(), b.getY() ) )
+                  .d( Math.max( a.getX(), b.getX() ) )
+                  .d( Math.max( a.getY(), b.getY() ) );
+            m_aOut.text( aURI );
+        }
+    }
+
+    private Point2D toDevice( double x, double y )
+    {
+        return m_aDevXform.transform( new Point2D.Double( x, y ), null );
+    }
+
+    // ---- state emission ---------------------------------------------------
+
+    /**
+     * Declares everything the coming operation depends on, restating only what
+     * has actually changed since the last one.
+     */
+    private void beginOp( double[] aCtm, boolean bStroke, boolean bFill )
+        throws IOException
+    {
+        syncClip();
+
+        if( !sameArray( m_aLastCtm, aCtm ) )
+        {
+            m_aOut.cmd( "updateCtm" );
+            for( int i = 0; i < 6; ++i )
+                m_aOut.d( aCtm[i] );
+            m_aOut.eol();
+            m_aLastCtm = aCtm.clone();
+        }
+
+        final PDGraphicsState aGS = getGraphicsState();
+
+        if( bFill )
+        {
+            final double[] aCol = rgba( aGS.getNonStrokingColorSpace(),
+                                        aGS.getNonStrokingColor(),
+                                        aGS.getNonStrokeAlphaConstant() );
+            if( !sameArray( m_aLastFill, aCol ) )
+            {
+                emitColor( "updateFillColor", aCol );
+                m_aLastFill = aCol;
+            }
+        }
+
+        if( bStroke )
+        {
+            final double[] aCol = rgba( aGS.getStrokingColorSpace(),
+                                        aGS.getStrokingColor(),
+                                        aGS.getAlphaConstant() );
+            if( !sameArray( m_aLastStroke, aCol ) )
+            {
+                emitColor( "updateStrokeColor", aCol );
+                m_aLastStroke = aCol;
+            }
+        }
+
+        if( bStroke )
+        {
+            // Line width is in user space; the consumer scales it by the CTM.
+            if( aGS.getLineWidth() != m_fLastLineWidth )
+            {
+                m_aOut.cmd( "updateLineWidth" ).d( aGS.getLineWidth() ).eol();
+                m_fLastLineWidth = aGS.getLineWidth();
+            }
+            if( aGS.getLineCap() != m_nLastLineCap )
+            {
+                m_aOut.cmd( "updateLineCap" ).i( aGS.getLineCap() ).eol();
+                m_nLastLineCap = aGS.getLineCap();
+            }
+            if( aGS.getLineJoin() != m_nLastLineJoin )
+            {
+                m_aOut.cmd( "updateLineJoin" ).i( aGS.getLineJoin() ).eol();
+                m_nLastLineJoin = aGS.getLineJoin();
+            }
+            if( aGS.getMiterLimit() != m_fLastMiterLimit )
+            {
+                m_aOut.cmd( "updateMiterLimit" ).d( aGS.getMiterLimit() 
).eol();
+                m_fLastMiterLimit = aGS.getMiterLimit();
+            }
+            emitDash( aGS.getLineDashPattern() );
+        }
+    }
+
+    /**
+     * Keeps the declared clip in step with the document's.
+     *
+     * <p>The protocol can only ever narrow a clip ({@code clipPath}
+     * intersects), so widening one means unwinding it with
+     * {@code restoreState}.  Rather than bracket every operation, one bracket
+     * is held open for as long as the clip stays the same -- which for a body
+     * of text under a single clip is the whole run.  Unwinding also discards
+     * the emitted-state cache, since the consumer has just popped its own
+     * copy of that state.</p>
+     */
+    private void syncClip() throws IOException
+    {
+        final Area aClip = effectiveClip();
+        if( aClip == m_aActiveClip )
+            return;
+
+        if( m_bClipBracketOpen )
+        {
+            m_aOut.cmd( "restoreState" ).eol();
+            m_bClipBracketOpen = false;
+            invalidateStateCache();
+        }
+
+        m_aActiveClip = aClip;
+
+        if( aClip != null )
+        {
+            final List<SubPath> aSubs = flatten( aClip );
+            if( !aSubs.isEmpty() )
+            {
+                m_aOut.cmd( "saveState" ).eol();
+                m_bClipBracketOpen = true;
+                invalidateStateCache();
+
+                m_aOut.cmd( "clipPath" );
+                writePath( aSubs );
+                m_aOut.eol();
+            }
+        }
+    }
+
+    /**
+     * The current clip, or null when it does not actually restrict anything --
+     * the consumer already clips to the page bounds on startPage.
+     */
+    private Area effectiveClip()
+    {
+        final Area aClip = getGraphicsState().getCurrentClippingPath();
+        if( aClip == null )
+            return null;
+
+        return aClip.contains( m_aCropBox.getLowerLeftX(), 
m_aCropBox.getLowerLeftY(),
+                               m_aCropBox.getWidth(), m_aCropBox.getHeight() )
+               ? null : aClip;
+    }
+
+    /** Closes any open clip bracket; called once the page is finished. */
+    private void closeClipBracket() throws IOException
+    {
+        if( m_bClipBracketOpen )
+        {
+            m_aOut.cmd( "restoreState" ).eol();
+            m_bClipBracketOpen = false;
+            invalidateStateCache();
+        }
+        m_aActiveClip = null;
+    }
+
+    private void invalidateStateCache()
+    {
+        m_aLastCtm = null;
+        m_aLastFill = null;
+        m_aLastStroke = null;
+        m_fLastLineWidth = Double.NaN;
+        m_nLastLineCap = -1;
+        m_nLastLineJoin = -1;
+        m_fLastMiterLimit = Double.NaN;
+        m_aLastDash = null;
+        m_nLastFontId = -1;
+        m_fLastFontSize = Double.NaN;
+        m_nLastRenderMode = -1;
+    }
+
+    private static boolean sameArray( double[] a, double[] b )
+    {
+        if( a == null || b == null )
+            return false;
+        for( int i = 0; i < a.length; ++i )
+        {
+            if( a[i] != b[i] )
+                return false;
+        }
+        return true;
+    }
+
+    private void emitColor( String aCommand, double[] aRGBA ) throws 
IOException
+    {
+        m_aOut.cmd( aCommand ).d( aRGBA[0] ).d( aRGBA[1] ).d( aRGBA[2] )
+              .d( aRGBA[3] ).eol();
+    }
+
+    /** Resolves a PDF colour to sRGB plus alpha, defaulting to opaque black. 
*/
+    private static double[] rgba( PDColorSpace aCS, PDColor aColor, double 
fAlpha )
+    {
+        float[] aRGB = { 0f, 0f, 0f };
+        if( aCS != null && aColor != null )
+        {
+            try
+            {
+                aRGB = aCS.toRGB( aColor.getComponents() );
+            }
+            catch( Exception e )
+            {
+                // An unsupported or malformed colour space costs this colour,
+                // not the page; black is the PDF default anyway.
+            }
+        }
+        return new double[] { aRGB[0], aRGB[1], aRGB[2], fAlpha };
+    }
+
+    private void emitDash( PDLineDashPattern aDash ) throws IOException
+    {
+        final StringBuilder aBuf = new StringBuilder( 32 );
+        if( aDash != null && aDash.getDashArray() != null
+            && aDash.getDashArray().length != 0 )
+        {
+            final float[] aArray = aDash.getDashArray();
+            aBuf.append( aDash.getPhase() ).append( ' ' ).append( 
aArray.length );
+            for( int i = 0; i < aArray.length; ++i )
+                aBuf.append( ' ' ).append( aArray[i] );
+        }
+
+        final String aKey = aBuf.toString();
+        if( aKey.equals( m_aLastDash ) )
+            return;
+        m_aLastDash = aKey;
+
+        if( aDash == null || aDash.getDashArray() == null
+            || aDash.getDashArray().length == 0 )
+        {
+            m_aOut.cmd( "updateLineDash" ).eol(); // empty means solid
+            return;
+        }
+
+        final float[] aArray = aDash.getDashArray();
+        m_aOut.cmd( "updateLineDash" ).d( aDash.getPhase() ).i( aArray.length 
);
+        for( int i = 0; i < aArray.length; ++i )
+            m_aOut.d( aArray[i] );
+        m_aOut.eol();
+    }
+
+    /**
+     * Declares the current clip, unless it is the whole page -- the consumer
+     * already clips to the page bounds on startPage, so re-stating it would
+     * only add work and rounding error.
+     */
+    private void emitClip() throws IOException
+    {
+        final Area aClip = getGraphicsState().getCurrentClippingPath();
+        if( aClip == null )
+            return;
+
+        if( aClip.contains( m_aCropBox.getLowerLeftX(), 
m_aCropBox.getLowerLeftY(),
+                            m_aCropBox.getWidth(), m_aCropBox.getHeight() ) )
+            return;
+
+        final List<SubPath> aSubs = flatten( aClip );
+        if( aSubs.isEmpty() )
+            return;
+
+        m_aOut.cmd( "clipPath" );
+        writePath( aSubs );
+        m_aOut.eol();
+    }
+
+    // ---- path collection --------------------------------------------------
+
+    public void moveTo( float x, float y )
+    {
+        m_aCurrent = new SubPath();
+        m_aPath.add( m_aCurrent );
+        m_aCurrent.aPoints.add( new double[] { x, y, 0 } );
+        m_aCurrentPoint = new Point2D.Double( x, y );
+    }
+
+    public void lineTo( float x, float y )
+    {
+        if( m_aCurrent == null )
+            moveTo( x, y );
+        else
+        {
+            m_aCurrent.aPoints.add( new double[] { x, y, 0 } );
+            m_aCurrentPoint = new Point2D.Double( x, y );
+        }
+    }
+
+    public void curveTo( float x1, float y1, float x2, float y2, float x3, 
float y3 )
+    {
+        if( m_aCurrent == null )
+            moveTo( x1, y1 );
+
+        // Two control points flagged 1, then the on-curve endpoint flagged 0 
--
+        // the consumer folds exactly that triple back into a bezier segment.
+        m_aCurrent.aPoints.add( new double[] { x1, y1, 1 } );
+        m_aCurrent.aPoints.add( new double[] { x2, y2, 1 } );
+        m_aCurrent.aPoints.add( new double[] { x3, y3, 0 } );
+        m_aCurrentPoint = new Point2D.Double( x3, y3 );
+    }
+
+    public void appendRectangle( Point2D p0, Point2D p1, Point2D p2, Point2D 
p3 )
+    {
+        m_aCurrent = new SubPath();
+        m_aPath.add( m_aCurrent );
+        m_aCurrent.aPoints.add( new double[] { p0.getX(), p0.getY(), 0 } );
+        m_aCurrent.aPoints.add( new double[] { p1.getX(), p1.getY(), 0 } );
+        m_aCurrent.aPoints.add( new double[] { p2.getX(), p2.getY(), 0 } );
+        m_aCurrent.aPoints.add( new double[] { p3.getX(), p3.getY(), 0 } );
+        m_aCurrent.bClosed = true;
+        m_aCurrentPoint = new Point2D.Double( p0.getX(), p0.getY() );
+    }
+
+    public void closePath()
+    {
+        if( m_aCurrent != null )
+            m_aCurrent.bClosed = true;
+    }
+
+    public Point2D getCurrentPoint()
+    {
+        return m_aCurrentPoint;
+    }
+
+    public void clip( int nWindingRule )
+    {
+        // W/W* only marks the intent; the clip is taken from the path when the
+        // painting operator that terminates it arrives.
+        m_nPendingClip = nWindingRule;
+    }
+
+    public void endPath()
+    {
+        applyPendingClip();
+        m_aPath.clear();
+        m_aCurrent = null;
+    }
+
+    private void applyPendingClip()
+    {
+        if( m_nPendingClip == -1 || m_aPath.isEmpty() )
+        {
+            m_nPendingClip = -1;
+            return;
+        }
+
+        final GeneralPath aPath = new GeneralPath(
+            m_nPendingClip == PathIterator.WIND_EVEN_ODD
+                ? Path2D.WIND_EVEN_ODD : Path2D.WIND_NON_ZERO );
+
+        for( SubPath aSub : m_aPath )
+        {
+            final List<double[]> aPts = aSub.aPoints;
+            if( aPts.isEmpty() )
+                continue;
+
+            aPath.moveTo( aPts.get( 0 )[0], aPts.get( 0 )[1] );
+            for( int i = 1; i < aPts.size(); ++i )
+            {
+                // Control points are approximated by their chord here: this
+                // path is only ever used as a clip region, never drawn.
+                aPath.lineTo( aPts.get( i )[0], aPts.get( i )[1] );
+            }
+            if( aSub.bClosed )
+                aPath.closePath();
+        }
+
+        getGraphicsState().intersectClippingPath( aPath );
+        m_nPendingClip = -1;
+    }
+
+    // ---- path painting ----------------------------------------------------
+
+    public void strokePath() throws IOException
+    {
+        paint( true, false, false );
+    }
+
+    public void fillPath( int nWindingRule ) throws IOException
+    {
+        paint( false, true, nWindingRule == PathIterator.WIND_EVEN_ODD );
+    }
+
+    public void fillAndStrokePath( int nWindingRule ) throws IOException
+    {
+        paint( true, true, nWindingRule == PathIterator.WIND_EVEN_ODD );
+    }
+
+    private void paint( boolean bStroke, boolean bFill, boolean bEvenOdd )
+        throws IOException
+    {
+        endTextRun();
+
+        if( !m_aPath.isEmpty() )
+        {
+            beginOp( m_aDevCtm, bStroke, bFill );
+
+            if( bFill )
+            {
+                m_aOut.cmd( bEvenOdd ? "eoFillPath" : "fillPath" );
+                writePath( m_aPath );
+                m_aOut.eol();
+            }
+            if( bStroke )
+            {
+                m_aOut.cmd( "strokePath" );
+                writePath( m_aPath );
+                m_aOut.eol();
+            }
+        }
+
+        applyPendingClip();
+        m_aPath.clear();
+        m_aCurrent = null;
+    }
+
+    private void writePath( List<SubPath> aSubs ) throws IOException
+    {
+        for( SubPath aSub : aSubs )
+        {
+            if( aSub.aPoints.isEmpty() )
+                continue;
+
+            m_aOut.tok( "subpath" ).i( aSub.bClosed ? 1 : 0 );
+            for( double[] aPt : aSub.aPoints )
+                m_aOut.d( aPt[0] ).d( aPt[1] ).i( (int) aPt[2] );
+        }
+    }
+
+    /** Flattens an AWT area into protocol subpaths (straight segments only). 
*/
+    private static List<SubPath> flatten( Area aArea )
+    {
+        final List<SubPath> aRes = new ArrayList<SubPath>();
+        final PathIterator it = aArea.getPathIterator( null, 0.1 );
+        final double[] aSeg = new double[6];
+        SubPath aCur = null;
+
+        while( !it.isDone() )
+        {
+            switch( it.currentSegment( aSeg ) )
+            {
+                case PathIterator.SEG_MOVETO:
+                    aCur = new SubPath();
+                    aRes.add( aCur );
+                    aCur.aPoints.add( new double[] { aSeg[0], aSeg[1], 0 } );
+                    break;
+                case PathIterator.SEG_LINETO:
+                    if( aCur != null )
+                        aCur.aPoints.add( new double[] { aSeg[0], aSeg[1], 0 } 
);
+                    break;
+                case PathIterator.SEG_CLOSE:
+                    if( aCur != null )
+                        aCur.bClosed = true;
+                    break;
+                default:
+                    break; // flattened iterator yields no curves
+            }
+            it.next();
+        }
+        return aRes;
+    }
+
+    // ---- text -------------------------------------------------------------
+
+    @Override
+    protected void showGlyph( Matrix aTrm, PDFont aFont, int nCode, Vector 
aDisplacement )
+        throws IOException
+    {
+        final String aText = safeToUnicode( aFont, nCode );
+
+        if( aText != null && aText.length() != 0 )
+        {
+            // The glyph rectangle goes out in PDF USER space, like paths and
+            // for the same reason: pdfiprocessor.cxx transforms it by the
+            // declared CTM (drawCharGlyphs -> calcTransformedRectBounds).
+            // Emitting device coordinates here means the page transform is
+            // applied twice, putting every glyph a hundred times too far out
+            // and a hundred times too large -- text frames metres wide, far 
off
+            // the canvas, and so invisible rather than obviously wrong.
+            final AffineTransform aTextXform = aTrm.createAffineTransform();
+
+            final double fXScale = Math.hypot( aTextXform.getScaleX(), 
aTextXform.getShearY() );
+            final double fYScale = Math.hypot( aTextXform.getShearX(), 
aTextXform.getScaleY() );
+
+            final double fOriginX = aTextXform.getTranslateX();
+            final double fBaseY = aTextXform.getTranslateY();
+
+            double fAscent = 0.75; // a reasonable em fraction when unstated
+            final PDFontDescriptor aFD = aFont.getFontDescriptor();
+            if( aFD != null && aFD.getAscent() > 0 )
+                fAscent = aFD.getAscent() / 1000.0;
+
+            // User space is y-UP, so the top of the glyph is above the
+            // baseline and the rectangle runs downwards from it -- the same
+            // (top, top - height) convention poppler emits.
+            final double fTop = fBaseY + fAscent * fYScale;
+            final double fWidth = aDisplacement.getX() * fXScale;
+
+            // The font SIZE, unlike the rectangle, is a device-space quantity:
+            // drawtreevisiting.cxx converts it back with size*72/7200.  This 
is
+            // poppler's getTransformedFontSize().
+            final AffineTransform aComposed = new AffineTransform( m_aDevXform 
);
+            aComposed.concatenate( aTextXform );
+            final double fSizeDevice =
+                Math.hypot( aComposed.getShearX(), aComposed.getScaleY() );
+
+            beginOp( m_aDevCtm, false, true );
+
+            emitFont( aFont, fSizeDevice );
+
+            final PDTextState aTS = getGraphicsState().getTextState();
+            if( aTS.getRenderingMode().ordinal() != m_nLastRenderMode )
+            {
+                m_nLastRenderMode = aTS.getRenderingMode().ordinal();
+                m_aOut.cmd( "setTextRenderMode" ).i( m_nLastRenderMode ).eol();
+            }
+
+            // The font matrix carries orientation, shear and aspect -- no page
+            // transform, and deliberately NO overall scale.
+            //
+            // The consumer applies this matrix as a transform about the 
glyph's
+            // own origin (pdfiprocessor.cxx getTransformGlyphContext) *and*
+            // separately sizes the text from the font size above.  A document
+            // that puts its scale in Tm rather than in Tf -- [6 0 0 6] with
+            // Tf 1, which plenty of generators do -- would therefore be scaled
+            // by 6 twice over, throwing the text off the page.  That is 
exactly
+            // what poppler does here: it sends getTransformedFontSize(), which
+            // already includes Tm's scale, alongside the raw Tm.
+            //
+            // Dividing by Tm's own vertical scale removes the double count
+            // while keeping rotation, shear and the horizontal/vertical aspect
+            // ratio, which the single font-size number cannot express.
+            final Matrix aTm = getTextMatrix();
+            double fTmScale = Math.hypot( aTm.getShearX(), aTm.getScaleY() );
+            if( fTmScale < 1e-9 )
+                fTmScale = 1.0;
+
+            m_aOut.cmd( "drawChar" )
+                  .d( fOriginX )
+                  .d( fTop )
+                  .d( fOriginX + ( fWidth != 0.0 ? fWidth : fYScale ) )
+                  .d( fTop - fYScale )
+                  .d( aTm.getScaleX() / fTmScale ).d( aTm.getShearX() / 
fTmScale )
+                  .d( aTm.getShearY() / fTmScale ).d( aTm.getScaleY() / 
fTmScale );
+            m_aOut.text( aText );
+            m_bInText = true;
+        }
+
+        super.showGlyph( aTrm, aFont, nCode, aDisplacement );
+    }
+
+    /**
+     * A font whose /ToUnicode is missing or broken makes toUnicode() throw or
+     * return null.  That costs the glyph, never the document -- an unmappable
+     * glyph is exactly the case where the rest of the page still matters.
+     */
+    private static String safeToUnicode( PDFont aFont, int nCode )
+    {
+        try
+        {
+            return aFont.toUnicode( nCode );
+        }
+        catch( Exception e )
+        {
+            return null;
+        }
+    }
+
+    private void emitFont( PDFont aFont, double fSizeDevice ) throws 
IOException
+    {
+        Long aId = m_aFontIds.get( aFont );
+        if( aId == null )
+        {
+            aId = Long.valueOf( m_pNextFontId[0]++ );
+            m_aFontIds.put( aFont, aId );
+        }
+
+        String aName = aFont.getName();
+        if( aName == null || aName.length() == 0 )
+            aName = "Arial";
+
+        boolean bBold = false, bItalic = false;
+        final PDFontDescriptor aFD = aFont.getFontDescriptor();
+        if( aFD != null )
+        {
+            bBold = aFD.isForceBold() || aFD.getFontWeight() >= 600;
+            bItalic = aFD.isItalic() || aFD.getItalicAngle() != 0;
+        }
+
+        // fileLen 0: we never ship the embedded font file.  The consumer only
+        // wants it to recover a family name via FontIdentificator, and PDFBox
+        // has already given us one -- including the subset tag the consumer's
+        // parseFontFamilyName() knows how to strip.
+        if( aId.longValue() == m_nLastFontId && fSizeDevice == m_fLastFontSize 
)
+            return;
+        m_nLastFontId = aId.longValue();
+        m_fLastFontSize = fSizeDevice;
+
+        m_aOut.cmd( "updateFont" )
+              .l( aId.longValue() )
+              .i( aFont.isEmbedded() ? 1 : 0 )
+              .i( bBold ? 1 : 0 )
+              .i( bItalic ? 1 : 0 )
+              .i( 0 )
+              .d( fSizeDevice )
+              .i( 0 );
+        m_aOut.text( aName );
+    }
+
+    private void endTextRun() throws IOException
+    {
+        if( m_bInText )
+        {
+            m_aOut.cmd( "endTextObject" ).eol();
+            m_bInText = false;
+        }
+    }
+
+    // ---- images -----------------------------------------------------------
+
+    public void drawImage( PDImage aImage ) throws IOException
+    {
+        endTextRun();
+
+        // The image occupies the unit square under the current CTM, so the
+        // consumer needs that composed with the page transform.
+        final AffineTransform aComposed = new AffineTransform( m_aDevXform );
+        aComposed.concatenate(
+            
getGraphicsState().getCurrentTransformationMatrix().createAffineTransform() );
+
+        final double[] aCtm = {
+            aComposed.getScaleX(), aComposed.getShearY(),
+            aComposed.getShearX(), aComposed.getScaleY(),
+            aComposed.getTranslateX(), aComposed.getTranslateY() };
+
+        // Prefer the image's own JPEG bytes, untouched.  Decoding and
+        // re-encoding to PNG is lossless but enormous -- a 19.7 MB book of
+        // photographs produced 76 MB of PNG, four times the whole source file
+        // -- and costs a decode plus a compress per image.  The consumer takes
+        // JPEG directly (readImageImpl), so the common case converts nothing
+        // and never builds a BufferedImage at all.
+        byte[] aData = originalJpeg( aImage );
+        String aFormat = "JPEG";
+        int nWidth, nHeight;
+
+        if( aData != null )
+        {
+            nWidth  = aImage.getWidth();
+            nHeight = aImage.getHeight();
+        }
+        else
+        {
+            final BufferedImage aBitmap;
+            try
+            {
+                aBitmap = aImage.getImage();
+            }
+            catch( Exception e )
+            {
+                // An undecodable image (a broken JPX or JBIG2 stream, say)
+                // costs the image and nothing else.
+                return;
+            }
+            if( aBitmap == null )
+                return;
+
+            // The source was already lossy, so it is photographic by
+            // construction and re-encoding it losslessly is the wrong trade:
+            // PNG made a 19.7 MB book into 76 MB.  Staying lossy costs one
+            // recompression of content that was never crisp.  Anything stored
+            // losslessly -- line art, screenshots, masks -- keeps PNG, where
+            // JPEG would smear edges for no gain.
+            if( wasLossy( aImage ) && !aBitmap.getColorModel().hasAlpha() )
+            {
+                aData   = encodeJpeg( aBitmap );
+                aFormat = "JPEG";
+            }
+            if( aData == null )
+            {
+                aData   = encodePng( aBitmap );
+                aFormat = "PNG";
+            }
+            nWidth  = aBitmap.getWidth();
+            nHeight = aBitmap.getHeight();
+        }
+        if( aData == null )
+            return;
+
+        beginOp( aCtm, false, true );
+
+        // A stencil mask paints the current fill colour through the image, so
+        // the consumer wants it as drawMask rather than drawImage.
+        m_aOut.cmd( aImage.isStencil() ? "drawMask" : "drawImage" )
+              .i( nWidth ).i( nHeight ).i( 0 )
+              .tok( aFormat ).i( aData.length ).eol();
+        m_aOut.binary( aData );
+    }
+
+    /**
+     * The image's own JPEG bytes, when passing them through unchanged is
+     * faithful -- otherwise null, and the caller re-encodes.
+     *
+     * <p>Every condition here is a way the stored bytes alone would not
+     * reproduce what the page shows: a stencil or an explicit mask needs the
+     * mask applied, a soft mask needs alpha that JPEG cannot carry, a /Decode
+     * array remaps samples, and a four-component (CMYK) JPEG is the case
+     * decoders most often disagree about.  In all of those, decoding to a
+     * bitmap and re-encoding is the honest answer.</p>
+     */
+    private static byte[] originalJpeg( PDImage aImage )
+    {
+        if( !( aImage instanceof PDImageXObject ) )
+            return null;
+
+        final PDImageXObject aXObj = (PDImageXObject) aImage;
+        try
+        {
+            if( !"jpg".equals( aXObj.getSuffix() ) )
+                return null;
+            if( aXObj.isStencil() || aXObj.getDecode() != null )
+                return null;
+            if( aXObj.getSoftMask() != null || aXObj.getMask() != null )
+                return null;
+
+            final PDColorSpace aCS = aXObj.getColorSpace();
+            if( aCS == null || aCS.getNumberOfComponents() > 3 )
+                return null;
+
+            // stop before DCTDecode: the stream as stored, still JPEG
+            final InputStream aIn =
+                aXObj.createInputStream( Collections.singletonList( 
"DCTDecode" ) );
+            try
+            {
+                final ByteArrayOutputStream aBuf = new ByteArrayOutputStream( 
1 << 16 );
+                final byte[] aChunk = new byte[8192];
+                int n;
+                while( ( n = aIn.read( aChunk ) ) > 0 )
+                    aBuf.write( aChunk, 0, n );
+                return aBuf.size() > 0 ? aBuf.toByteArray() : null;
+            }
+            finally
+            {
+                aIn.close();
+            }
+        }
+        catch( Exception e )
+        {
+            return null; // anything unexpected: fall back to re-encoding
+        }
+    }
+
+    /** Whether the image was stored in a lossy format to begin with. */
+    private static boolean wasLossy( PDImage aImage )
+    {
+        final String aSuffix = aImage.getSuffix();
+        return "jpg".equals( aSuffix ) || "jpx".equals( aSuffix );
+    }
+
+    /**
+     * Re-encodes as JPEG.  Used only for images that arrived lossy and whose
+     * colour PDFBox has already resolved to sRGB -- notably the CMYK JPEGs 
that
+     * {@link #originalJpeg} refuses to pass through untouched, since decoders
+     * disagree about Adobe's inverted CMYK and a wrong guess inverts the page.
+     */
+    private static byte[] encodeJpeg( BufferedImage aImage )
+    {
+        ImageWriter aWriter = null;
+        try
+        {
+            // JPEG cannot store alpha, and a writer handed ARGB either fails 
or
+            // writes colours that are subtly wrong; go through opaque RGB.
+            BufferedImage aRgb = aImage;
+            if( aImage.getType() != BufferedImage.TYPE_INT_RGB )
+            {
+                aRgb = new BufferedImage( aImage.getWidth(), 
aImage.getHeight(),
+                                          BufferedImage.TYPE_INT_RGB );
+                final java.awt.Graphics2D g = aRgb.createGraphics();
+                g.drawImage( aImage, 0, 0, null );
+                g.dispose();
+            }
+
+            final java.util.Iterator<ImageWriter> it =
+                ImageIO.getImageWritersByFormatName( "jpeg" );
+            if( !it.hasNext() )
+                return null;
+            aWriter = it.next();
+
+            final ImageWriteParam aParam = aWriter.getDefaultWriteParam();
+            if( aParam.canWriteCompressed() )
+            {
+                aParam.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
+                aParam.setCompressionQuality( 0.85f );
+            }
+
+            final ByteArrayOutputStream aBuf = new ByteArrayOutputStream( 1 << 
16 );
+            final ImageOutputStream aOut = ImageIO.createImageOutputStream( 
aBuf );
+            try
+            {
+                aWriter.setOutput( aOut );
+                aWriter.write( null, new IIOImage( aRgb, null, null ), aParam 
);
+            }
+            finally
+            {
+                aOut.close();
+            }
+            return aBuf.size() > 0 ? aBuf.toByteArray() : null;
+        }
+        catch( Exception e )
+        {
+            return null; // caller falls back to PNG
+        }
+        finally
+        {
+            if( aWriter != null )
+                aWriter.dispose();
+        }
+    }
+
+    /**
+     * Re-encodes to PNG for the wire.
+     *
+     * <p>Deliberately not the hand-written encoder the poppler helper uses
+     * (xpdfwrapper/pnghelper.cxx): that one computes scanline offsets in
+     * 32-bit arithmetic from PDF-controlled dimensions and writes past its
+     * buffer, which is AOO-2026-014.  ImageIO is bounds-safe and needs no
+     * maintenance from us.</p>
+     */
+    private static byte[] encodePng( BufferedImage aImage )
+    {
+        try
+        {
+            final ByteArrayOutputStream aBuf = new ByteArrayOutputStream( 1 << 
16 );
+            if( !ImageIO.write( aImage, "png", aBuf ) )
+                return null;
+            return aBuf.toByteArray();
+        }
+        catch( IOException e )
+        {
+            return null;
+        }
+    }
+
+    // ---- unsupported ------------------------------------------------------
+
+    public void shadingFill( COSName aName )
+    {
+        // Shadings (types 1-7, including mesh and coons patches) have no ODF
+        // equivalent beyond a plain gradient.  Dropping is honest; forcing
+        // them into a two-stop gradient would be a worse lie.
+    }
+}
diff --git 
a/main/sdext/source/pdfimport/pdfboxwrapper/src/org/apache/openoffice/pdfimport/PdfiWriter.java
 
b/main/sdext/source/pdfimport/pdfboxwrapper/src/org/apache/openoffice/pdfimport/PdfiWriter.java
new file mode 100644
index 0000000000..d0ccf52b56
--- /dev/null
+++ 
b/main/sdext/source/pdfimport/pdfboxwrapper/src/org/apache/openoffice/pdfimport/PdfiWriter.java
@@ -0,0 +1,190 @@
+/**************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************/
+
+package org.apache.openoffice.pdfimport;
+
+import java.io.BufferedOutputStream;
+import java.io.FileDescriptor;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Locale;
+
+/**
+ * Writes the pdfi helper protocol -- see PROTOCOL.md, which is the normative
+ * description; this class is one implementation of it.
+ *
+ * <p>v2 framing: commands and binary payloads share one stream, a payload
+ * following immediately after the newline of the line that stated its length.
+ * That is why everything here goes through a single {@link OutputStream} and
+ * why nothing ever flushes mid-document -- there is no second pipe to stay in
+ * step with.</p>
+ *
+ * <p><b>stdout is the protocol.</b> Nothing else in this process may write to
+ * it; diagnostics belong on stderr, which v2 deliberately leaves free.</p>
+ */
+final class PdfiWriter
+{
+    /**
+     * Device units per PDF point.
+     *
+     * <p>The consumer works in 1/7200 inch (PDFI_OUTDEV_RESOLUTION in
+     * pdfihelper.hxx), a PDF point is 1/72 inch, so a point is 100 device
+     * units.  Font sizes travel in the same unit -- drawtreevisiting.cxx
+     * converts back with {@code size*72/7200}.</p>
+     */
+    static final double DEVICE_UNITS_PER_POINT = 100.0;
+
+    /** Below this, a coordinate is noise from an inexact matrix product. */
+    private static final double EPSILON = 0.0000001;
+
+    private final OutputStream m_aOut;
+    private final StringBuilder m_aLine = new StringBuilder( 256 );
+
+    PdfiWriter()
+    {
+        m_aOut = new BufferedOutputStream(
+            new FileOutputStream( FileDescriptor.out ), 1 << 16 );
+    }
+
+    /** Matches normalize() in pdfioutdev_gpl.cxx: clamp denormal noise away. 
*/
+    static double normalize( double fValue )
+    {
+        return Math.abs( fValue ) < EPSILON ? 0.0 : fValue;
+    }
+
+    // ---- line assembly ----------------------------------------------------
+
+    PdfiWriter cmd( String aCommand )
+    {
+        if( m_aLine.length() != 0 )
+            throw new IllegalStateException( "unterminated command: " + 
m_aLine );
+        m_aLine.append( aCommand );
+        return this;
+    }
+
+    /**
+     * Appends a bare token to a line already in progress -- the {@code 
subpath}
+     * marker, an image format name.  Unlike {@link #cmd} this does not insist
+     * on being at the start of a line.
+     */
+    PdfiWriter tok( String aToken )
+    {
+        m_aLine.append( ' ' ).append( aToken );
+        return this;
+    }
+
+    PdfiWriter i( int nValue )
+    {
+        m_aLine.append( ' ' ).append( nValue );
+        return this;
+    }
+
+    PdfiWriter l( long nValue )
+    {
+        m_aLine.append( ' ' ).append( nValue );
+        return this;
+    }
+
+    /**
+     * Appends a number in the consumer's expected form: C {@code %f}, six
+     * decimals, always a dot.  Locale.ROOT is not decoration -- under a
+     * European default locale Java would emit {@code 1,5}, which the consumer
+     * reads with rtl::OString::toDouble() as 1.0, silently displacing
+     * everything on the page.
+     */
+    PdfiWriter d( double fValue )
+    {
+        m_aLine.append( ' ' )
+               .append( String.format( Locale.ROOT, "%f", normalize( fValue ) 
) );
+        return this;
+    }
+
+    /** Appends the trailing free-text field, escaped, and ends the line. */
+    void text( String aText ) throws IOException
+    {
+        m_aLine.append( ' ' );
+        escapeInto( aText, m_aLine );
+        eol();
+    }
+
+    void eol() throws IOException
+    {
+        m_aLine.append( '\n' );
+        // The grammar is ASCII; only the free-text fields carry non-ASCII, and
+        // those were already encoded to UTF-8 bytes by escapeInto().
+        final int nLen = m_aLine.length();
+        for( int i = 0; i < nLen; ++i )
+            m_aOut.write( m_aLine.charAt( i ) & 0xFF );
+        m_aLine.setLength( 0 );
+    }
+
+    /**
+     * Writes a binary payload.  Must directly follow the {@link #eol()} of the
+     * command that stated its length, with nothing in between.
+     */
+    void binary( byte[] aData ) throws IOException
+    {
+        if( m_aLine.length() != 0 )
+            throw new IllegalStateException( "payload before end of command" );
+        m_aOut.write( aData );
+    }
+
+    void finish() throws IOException
+    {
+        m_aOut.flush();
+    }
+
+    // ---- escaping ---------------------------------------------------------
+
+    /**
+     * Escapes the free-text fields of {@code drawChar}, {@code updateFont} and
+     * {@code drawLink}, which run to end of line.
+     *
+     * <p>Text is UTF-8, and each byte is appended as one char so that
+     * {@link #eol()} can write it out unchanged -- the consumer decodes the
+     * field with RTL_TEXTENCODING_UTF8.</p>
+     */
+    private static void escapeInto( String aText, StringBuilder aBuf )
+    {
+        final byte[] aUtf8;
+        try
+        {
+            aUtf8 = aText.getBytes( "UTF-8" );
+        }
+        catch( java.io.UnsupportedEncodingException e )
+        {
+            throw new AssertionError( "UTF-8 is required of every JVM" );
+        }
+
+        for( int i = 0; i < aUtf8.length; ++i )
+        {
+            final int c = aUtf8[i] & 0xFF;
+            switch( c )
+            {
+                case '\n': aBuf.append( '\\' ).append( 'n' ); break;
+                case '\r': aBuf.append( '\\' ).append( 'r' ); break;
+                case '\\': aBuf.append( '\\' ).append( '\\' ); break;
+                default:   aBuf.append( (char) c ); break;
+            }
+        }
+    }
+}
diff --git a/main/sdext/source/pdfimport/pdfimport.component 
b/main/sdext/source/pdfimport/pdfimport.component
new file mode 100644
index 0000000000..8ce9f46deb
--- /dev/null
+++ b/main/sdext/source/pdfimport/pdfimport.component
@@ -0,0 +1,53 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--***********************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ ***********************************************************-->
+
+<!-- Mirrors the table in source/pdfimport/services.cxx (lcl_getComponents).
+     The extension registered itself through component_writeInfo, which the
+     .component mechanism replaced; the names below are exactly the ones that
+     function wrote, because the configuration refers to them by string:
+
+       config/pdf_types.xcu        DetectService = ...PDFDetector
+       config/pdf_import_filter.xcu  UserData[0] = 
...{Draw,Impress,Writer}PDFImport
+       source/pdfimport/filterdet.cxx  ...HybridPDFImport, via the
+                                       *_pdf_addstream_import filters
+
+     All five declare com.sun.star.document.ImportFilter, which is what
+     component_writeInfo declared for them, the detector included; the
+     configuration reaches every one of them by implementation name. -->
+<component loader="com.sun.star.loader.SharedLibrary"
+    xmlns="http://openoffice.org/2010/uno-components";>
+  <implementation name="com.sun.star.comp.documents.HybridPDFImport">
+    <service name="com.sun.star.document.ImportFilter"/>
+  </implementation>
+  <implementation name="com.sun.star.comp.documents.WriterPDFImport">
+    <service name="com.sun.star.document.ImportFilter"/>
+  </implementation>
+  <implementation name="com.sun.star.comp.documents.DrawPDFImport">
+    <service name="com.sun.star.document.ImportFilter"/>
+  </implementation>
+  <implementation name="com.sun.star.comp.documents.ImpressPDFImport">
+    <service name="com.sun.star.document.ImportFilter"/>
+  </implementation>
+  <implementation name="com.sun.star.comp.documents.PDFDetector">
+    <service name="com.sun.star.document.ImportFilter"/>
+  </implementation>
+</component>
diff --git a/main/sdext/source/pdfimport/wrapper/pdfbackend.cxx 
b/main/sdext/source/pdfimport/wrapper/pdfbackend.cxx
new file mode 100644
index 0000000000..1049610163
--- /dev/null
+++ b/main/sdext/source/pdfimport/wrapper/pdfbackend.cxx
@@ -0,0 +1,330 @@
+/**************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ *************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_sdext.hxx"
+
+#include "pdfbackend.hxx"
+
+#include "osl/file.hxx"
+#include "osl/diagnose.h"
+#include "rtl/bootstrap.hxx"
+#include "rtl/ustrbuf.hxx"
+
+#include "com/sun/star/uno/XComponentContext.hpp"
+#include "com/sun/star/deployment/XPackageInformationProvider.hpp"
+
+#include "jvmfwk/framework.h"
+
+#include <boost/preprocessor/stringize.hpp>
+
+#ifndef PDFI_IMPL_IDENTIFIER
+# error define implementation name for pdfi extension, please!
+#endif
+
+using namespace com::sun::star;
+
+namespace pdfi
+{
+
+namespace
+{
+
+#ifdef WNT
+# define EXE_SUFFIX ".exe"
+#else
+# define EXE_SUFFIX ""
+#endif
+
+rtl::OUString toFileURL( const rtl::OUString& rPathOrURL );
+
+rtl::OUString stripTrailingSlashes( rtl::OUString aURL )
+{
+    while( aURL.getLength() && aURL[aURL.getLength()-1] == sal_Unicode('/') )
+        aURL = aURL.copy( 0, aURL.getLength()-1 );
+    return aURL;
+}
+
+/** Directory the helper programs live in, as a file URL without a trailing
+    slash.
+
+    Two layouts, both real.  Deployed as an .oxt the helpers sit inside the
+    extension, and only the deployment service knows where that was unpacked.
+    Built and staged directly into the install -- which is what the Bazel build
+    produces, and what anyone testing a change actually runs -- there is no
+    package at all and they sit in program/ beside soffice.  Ask the deployment
+    service first and fall back to the brand's program directory; empty means
+    neither answered, and the caller lets PATH decide.
+ */
+rtl::OUString getHelperLocation( const uno::Reference< uno::XComponentContext 
>& xContext )
+{
+    // An explicit override wins: a test fixture bootstraps a bare UNO context
+    // with neither a deployment service nor a brand layout, so this is the 
only
+    // way it can say where the helpers were built.
+    rtl::OUString aOverride;
+    rtl::Bootstrap::get( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( 
"PDFI_HELPER_DIR" ) ),
+                         aOverride );
+    if( aOverride.getLength() )
+        return stripTrailingSlashes( toFileURL( aOverride ) );
+
+    rtl::OUString aLocation;
+    try
+    {
+        uno::Reference< deployment::XPackageInformationProvider > xProvider(
+            xContext->getValueByName(
+                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
+                    
"/singletons/com.sun.star.deployment.PackageInformationProvider" ) ) ),
+            uno::UNO_QUERY );
+        if( xProvider.is() )
+            aLocation = xProvider->getPackageLocation(
+                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
+                    BOOST_PP_STRINGIZE(PDFI_IMPL_IDENTIFIER) ) ) );
+    }
+    catch( uno::Exception& )
+    {
+        // no deployment context -- fall back to PATH
+    }
+
+    if( aLocation.getLength() )
+        return stripTrailingSlashes( aLocation );
+
+    rtl::OUString aBrandDir;
+    rtl::Bootstrap::get( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( 
"BRAND_BASE_DIR" ) ),
+                         aBrandDir );
+    if( aBrandDir.getLength() )
+    {
+        rtl::OUStringBuffer aBuf( aBrandDir.getLength() + 8 );
+        aBuf.append( stripTrailingSlashes( aBrandDir ) );
+        aBuf.appendAscii( "/program" );
+        return aBuf.makeStringAndClear();
+    }
+
+    // URE-only bootstrap: no brand layout, but the libraries' own directory is
+    // still where a helper staged beside them would be.
+    rtl::OUString aUreLibDir;
+    rtl::Bootstrap::get( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( 
"URE_LIB_DIR" ) ),
+                         aUreLibDir );
+    return stripTrailingSlashes( aUreLibDir );
+}
+
+bool exists( const rtl::OUString& rFileURL )
+{
+    if( !rFileURL.getLength() )
+        return false;
+
+    osl::DirectoryItem aItem;
+    return osl::DirectoryItem::get( rFileURL, aItem ) == osl::FileBase::E_None;
+}
+
+/** Join a directory URL and a file name, returning the result only if the file
+    is really there.  An empty directory means "not deployed", in which case
+    there is nothing to probe and the caller falls back to PATH.
+ */
+rtl::OUString probe( const rtl::OUString& rDirURL, const sal_Char* pName )
+{
+    if( !rDirURL.getLength() )
+        return rtl::OUString();
+
+    rtl::OUStringBuffer aBuf( rDirURL.getLength() + 32 );
+    aBuf.append( rDirURL );
+    aBuf.appendAscii( "/" );
+    aBuf.appendAscii( pName );
+
+    const rtl::OUString aURL( aBuf.makeStringAndClear() );
+    return exists( aURL ) ? aURL : rtl::OUString();
+}
+
+/** Convert whatever a user put in a bootstrap variable -- a file URL or a
+    native path -- into a file URL.
+ */
+rtl::OUString toFileURL( const rtl::OUString& rPathOrURL )
+{
+    if( !rPathOrURL.getLength() )
+        return rtl::OUString();
+
+    if( rPathOrURL.compareToAscii( RTL_CONSTASCII_STRINGPARAM( "file://" ) ) 
== 0 )
+        return rPathOrURL;
+
+    rtl::OUString aURL;
+    if( osl::FileBase::getFileURLFromSystemPath( rPathOrURL, aURL ) == 
osl::FileBase::E_None )
+        return aURL;
+
+    return rtl::OUString();
+}
+
+/** Locate a java launcher.
+
+    Asked in order of how confident we are that the answer is the one the user
+    wants: an explicit override, then the JRE the office itself is configured
+    with, then the ambient JAVA_HOME, then a bare name for PATH to resolve.
+    The office's own selection outranks JAVA_HOME deliberately -- a machine
+    commonly has several JREs, and only one of them is the one the user
+    pointed the office at in Tools - Options - Java.
+ */
+rtl::OUString findJavaExecutable()
+{
+    rtl::OUString aOverride;
+    rtl::Bootstrap::get( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( 
"PDFI_JAVA" ) ),
+                         aOverride );
+    if( aOverride.getLength() )
+    {
+        const rtl::OUString aURL( toFileURL( aOverride ) );
+        if( exists( aURL ) )
+            return aURL;
+        OSL_TRACE( "pdfi: PDFI_JAVA set but no such file, ignoring" );
+    }
+
+    // the JRE the office is configured to use
+    JavaInfo* pInfo = NULL;
+    if( jfw_getSelectedJRE( &pInfo ) == JFW_E_NONE && pInfo != NULL )
+    {
+        const rtl::OUString aLocation( stripTrailingSlashes( pInfo->sLocation 
) );
+        jfw_freeJavaInfo( pInfo );
+
+        const rtl::OUString aJava( probe( aLocation, "bin/java" EXE_SUFFIX ) );
+        if( aJava.getLength() )
+            return aJava;
+    }
+
+    rtl::OUString aJavaHome;
+    if( rtl::Bootstrap::get( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( 
"JAVA_HOME" ) ),
+                             aJavaHome ) && aJavaHome.getLength() )
+    {
+        const rtl::OUString aJava( probe( toFileURL( aJavaHome ), "bin/java" 
EXE_SUFFIX ) );
+        if( aJava.getLength() )
+            return aJava;
+    }
+
+    // let osl_executeProcess's SEARCHPATH find it
+    return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "java" EXE_SUFFIX ) );
+}
+
+/** The PDFBox helper.  Apache-licensed, so it needs no licence firewall, but
+    it keeps the separate process anyway for containment (see PROTOCOL.md).
+ */
+PdfBackend makePdfBoxBackend( const rtl::OUString& rPkgDir )
+{
+    // The jar is what has to be present; java itself may legitimately come
+    // from PATH, so it cannot be the availability test.
+    //
+    // Two layouts again: at the root of an unpacked .oxt, or -- when staged
+    // straight into the install -- in program/classes, which is where every
+    // other jar in the product lives.
+    rtl::OUString aJar( probe( rPkgDir, "pdfimport-pdfbox.jar" ) );
+    if( !aJar.getLength() )
+        aJar = probe( rPkgDir, "classes/pdfimport-pdfbox.jar" );
+    if( !aJar.getLength() )
+        return PdfBackend();
+
+    rtl::OUString aJarPath;
+    if( osl::FileBase::getSystemPathFromFileURL( aJar, aJarPath ) != 
osl::FileBase::E_None )
+        return PdfBackend();
+
+    PdfBackend aRes;
+    aRes.aId = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "pdfbox" ) );
+    aRes.eBinaryChannel = BINARY_INLINE;
+    aRes.aProgram = findJavaExecutable();
+    aRes.aPrefixArgs.push_back( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( 
"-jar" ) ) );
+    aRes.aPrefixArgs.push_back( aJarPath );
+    return aRes;
+}
+
+/** Reserved for the PDFium helper.  Nothing else in the tree changes when it
+    lands: build the executable, drop it beside the jar, and it is preferred
+    automatically.
+ */
+PdfBackend makePdfiumBackend( const rtl::OUString& rPkgDir )
+{
+    PdfBackend aRes;
+    aRes.aId = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "pdfium" ) );
+    aRes.eBinaryChannel = BINARY_INLINE;
+    aRes.aProgram = probe( rPkgDir, "pdfiumimport" EXE_SUFFIX );
+    return aRes;
+}
+
+/** The original poppler helper.  Built only where poppler is available and
+    its GPL licence is acceptable, so it is normally absent.
+ */
+PdfBackend makeXpdfBackend( const rtl::OUString& rPkgDir )
+{
+    PdfBackend aRes;
+    aRes.aId = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "xpdf" ) );
+    aRes.eBinaryChannel = BINARY_ON_STDERR;
+    aRes.aProgram = probe( rPkgDir, "xpdfimport" EXE_SUFFIX );
+
+    if( !aRes.aProgram.getLength() && !rPkgDir.getLength() )
+    {
+        // undeployed build tree: let PATH answer, as this helper always did
+        aRes.aProgram = rtl::OUString(
+            RTL_CONSTASCII_USTRINGPARAM( "xpdfimport" EXE_SUFFIX ) );
+    }
+    return aRes;
+}
+
+const int PDFI_BACKEND_COUNT = 3;
+
+} // namespace
+
+PdfBackend selectPdfBackend( const uno::Reference< uno::XComponentContext >& 
xContext )
+{
+    const rtl::OUString aPkgDir( getHelperLocation( xContext ) );
+
+    rtl::OUString aWanted;
+    rtl::Bootstrap::get( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( 
"PDFI_BACKEND" ) ),
+                         aWanted );
+
+    // Preference order.  PDFBox first: it is the one that is licensed to ship,
+    // hence the one a stock build actually has.
+    PdfBackend aCandidates[PDFI_BACKEND_COUNT];
+    aCandidates[0] = makePdfBoxBackend( aPkgDir );
+    aCandidates[1] = makePdfiumBackend( aPkgDir );
+    aCandidates[2] = makeXpdfBackend( aPkgDir );
+
+    if( aWanted.getLength() )
+    {
+        // An explicit request must not silently fall through to a different
+        // engine -- that would make a comparison run attribute one backend's
+        // output to the other.
+        for( int i = 0; i < PDFI_BACKEND_COUNT; ++i )
+        {
+            if( !aCandidates[i].aId.equalsIgnoreAsciiCase( aWanted ) )
+                continue;
+
+            if( !aCandidates[i].isAvailable() )
+                OSL_TRACE( "pdfi: PDFI_BACKEND names an unavailable backend" );
+
+            return aCandidates[i].isAvailable() ? aCandidates[i] : 
PdfBackend();
+        }
+
+        OSL_TRACE( "pdfi: PDFI_BACKEND names an unknown backend" );
+        return PdfBackend();
+    }
+
+    for( int i = 0; i < PDFI_BACKEND_COUNT; ++i )
+    {
+        if( aCandidates[i].isAvailable() )
+            return aCandidates[i];
+    }
+
+    return PdfBackend();
+}
+
+} // namespace pdfi
diff --git a/main/sdext/source/pdfimport/wrapper/wrapper.cxx 
b/main/sdext/source/pdfimport/wrapper/wrapper.cxx
index 11ced3b346..a2bb29b6f9 100644
--- a/main/sdext/source/pdfimport/wrapper/wrapper.cxx
+++ b/main/sdext/source/pdfimport/wrapper/wrapper.cxx
@@ -25,6 +25,7 @@
 #include "precompiled_sdext.hxx"
 
 #include "contentsink.hxx"
+#include "pdfbackend.hxx"
 #include "pdfparse.hxx"
 #include "pdfihelper.hxx"
 
@@ -41,7 +42,6 @@
 #include "com/sun/star/io/XInputStream.hpp"
 #include "com/sun/star/uno/XComponentContext.hpp"
 #include "com/sun/star/awt/FontDescriptor.hpp"
-#include "com/sun/star/deployment/XPackageInformationProvider.hpp"
 #include "com/sun/star/beans/XMaterialHolder.hpp"
 #include "com/sun/star/rendering/PathCapType.hpp"
 #include "com/sun/star/rendering/PathJoinType.hpp"
@@ -60,21 +60,18 @@
 #include "basegfx/tools/unopolypolygon.hxx"
 
 #include <boost/bind.hpp>
-#include <boost/preprocessor/stringize.hpp>
 #include <boost/scoped_ptr.hpp>
 #include <boost/scoped_array.hpp>
 
 #include <unordered_map>
+#include <vector>
+#include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
 #include <ctype.h>
 
 #include "rtl/bootstrap.h"
 
-#ifndef PDFI_IMPL_IDENTIFIER
-# error define implementation name for pdfi extension, please!
-#endif
-
 using namespace com::sun::star;
 
 namespace pdfi
@@ -144,7 +141,7 @@ class Parser
 
     const uno::Reference<uno::XComponentContext> m_xContext;
     const ContentSinkSharedPtr                   m_pSink;
-    const oslFileHandle                          m_pErr;
+    const oslFileHandle                          m_pBinary;
     ::rtl::OString                               m_aLine;
     FontMapType                                  m_aFontMap;
     sal_Int32                                    m_nNextToken;
@@ -184,12 +181,18 @@ class Parser
 
 
 public:
+    /** @param pBinary
+            handle the binary payloads (embedded fonts, bitmaps) arrive on.
+            Which handle that is depends on the backend's framing -- stderr for
+            v1, the same stdout the commands come from for v2 -- and is the 
only
+            thing that differs between them.  See PROTOCOL.md.
+     */
     Parser( const ContentSinkSharedPtr&                   rSink,
-            oslFileHandle                                 pErr,
+            oslFileHandle                                 pBinary,
             const uno::Reference<uno::XComponentContext>& xContext ) :
         m_xContext(xContext),
         m_pSink(rSink),
-        m_pErr(pErr),
+        m_pBinary(pBinary),
         m_aLine(),
         m_aFontMap(101),
         m_nNextToken(-1),
@@ -293,7 +296,7 @@ void Parser::readBinaryData( uno::Sequence<sal_Int8>& rBuf )
     sal_uInt64          nBytesRead(0);
     oslFileError        nRes=osl_File_E_None;
     while( nFileLen &&
-           osl_File_E_None == (nRes=osl_readFile( m_pErr, pBuf, nFileLen, 
&nBytesRead )) )
+           osl_File_E_None == (nRes=osl_readFile( m_pBinary, pBuf, nFileLen, 
&nBytesRead )) )
     {
         pBuf += nBytesRead;
         nFileLen -= sal::static_int_cast<sal_Int32>(nBytesRead);
@@ -778,7 +781,7 @@ void Parser::readSoftMaskedImage()
 void Parser::parseLine( const ::rtl::OString& rLine )
 {
     OSL_PRECOND( m_pSink,         "Invalid sink" );
-    OSL_PRECOND( m_pErr,          "Invalid filehandle" );
+    OSL_PRECOND( m_pBinary,       "Invalid filehandle" );
     OSL_PRECOND( m_xContext.is(), "Invalid service factory" );
 
     m_nNextToken = 0; m_nCharIndex = 0; m_aLine = rLine;
@@ -992,29 +995,36 @@ bool xpdf_ImportFromFile( const ::rtl::OUString&          
                   rUR
     rtl::OUString aPwd( rPwd );
     bool bIsEncrypted = false;
     if( checkEncryption( aSysUPath, xIHdl, aPwd, bIsEncrypted, aDocName ) == 
false )
+    {
+        // Either the built-in parser could not read the file at all, or an
+        // encrypted document was not unlocked.  Distinguishing the two 
matters:
+        // the first is a bug, the second is the user cancelling.
+        fprintf( stderr, "pdfi: %s\n",
+                 bIsEncrypted ? "encrypted PDF was not unlocked"
+                              : "could not parse PDF structure (pdfparse)" );
         return false;
+    }
 
-    rtl::OUStringBuffer converterURL = 
rtl::OUString::createFromAscii("xpdfimport");
-
-    // retrieve package location url (xpdfimport executable is located there)
-    // ---------------------------------------------------
-    uno::Reference<deployment::XPackageInformationProvider> xProvider(
-        xContext->getValueByName(
-            
rtl::OUString::createFromAscii("/singletons/com.sun.star.deployment.PackageInformationProvider"
 )),
-        uno::UNO_QUERY);
-    if( xProvider.is() )
+    const PdfBackend aBackend( selectPdfBackend( xContext ) );
+    if( !aBackend.isAvailable() )
     {
-        converterURL.insert(
-            0,
-            rtl::OUString::createFromAscii("/"));
-        converterURL.insert(
-            0,
-            xProvider->getPackageLocation(
-                rtl::OUString::createFromAscii(
-                    BOOST_PP_STRINGIZE(PDFI_IMPL_IDENTIFIER))));
+        // Say so out loud.  The only signal a caller gets from here is a false
+        // return, which odfConvert turns into an output file holding nothing
+        // but an XML declaration -- a symptom that says nothing about its
+        // cause.  stderr is free in v2 framing; use it.
+        fprintf( stderr,
+                 "pdfi: no PDF import backend found.\n"
+                 "      Looked for pdfimport-pdfbox.jar (also under 
classes/),\n"
+                 "      pdfiumimport and xpdfimport.  Set PDFI_HELPER_DIR to\n"
+                 "      the directory holding one of them.\n" );
+        return false;
     }
 
-    // spawn separate process to keep LGPL/GPL code apart.
+    // Spawn a separate process.  This began as a licence firewall -- the only
+    // backend linked poppler, which may not be linked into an Apache-licensed
+    // soffice.bin -- but it is kept for every backend, licence or not: a PDF 
is
+    // untrusted input, and a fault in the parser should cost one document
+    // rather than the user's session.
     // ---------------------------------------------------
     rtl_uString** ppEnv = NULL;
     sal_uInt32 nEnv = 0;
@@ -1032,17 +1042,23 @@ bool xpdf_ImportFromFile( const ::rtl::OUString&        
                     rUR
     nEnv = 1;
     #endif
 
-    rtl_uString*  args[] = { aSysUPath.pData };
-    sal_Int32 nArgs = 1;
+    // <backend prefix args...> <pdf path>; the path is always last
+    std::vector< rtl::OUString > aArgStrings( aBackend.aPrefixArgs );
+    aArgStrings.push_back( aSysUPath );
+
+    std::vector< rtl_uString* > aArgs;
+    aArgs.reserve( aArgStrings.size() );
+    for( size_t nArg = 0; nArg < aArgStrings.size(); ++nArg )
+        aArgs.push_back( aArgStrings[nArg].pData );
 
     oslProcess    aProcess;
     oslFileHandle pIn  = NULL;
     oslFileHandle pOut = NULL;
     oslFileHandle pErr = NULL;
     const oslProcessError eErr =
-        
osl_executeProcess_WithRedirectedIO(converterURL.makeStringAndClear().pData,
-                                            args,
-                                            nArgs,
+        osl_executeProcess_WithRedirectedIO(aBackend.aProgram.pData,
+                                            &aArgs[0],
+                                            sal_Int32(aArgs.size()),
                                             
osl_Process_SEARCHPATH|osl_Process_HIDDEN,
                                             osl_getCurrentSecurity(),
                                             0, ppEnv, nEnv,
@@ -1052,7 +1068,13 @@ bool xpdf_ImportFromFile( const ::rtl::OUString&         
                    rUR
     try
     {
         if( eErr!=osl_Process_E_None )
+        {
+            const rtl::OString aProgram(
+                rtl::OUStringToOString( aBackend.aProgram, 
RTL_TEXTENCODING_UTF8 ) );
+            fprintf( stderr, "pdfi: could not start backend '%s' (osl error 
%d)\n",
+                     aProgram.getStr(), (int)eErr );
             return false;
+        }
 
         if( pIn )
         {
@@ -1065,23 +1087,48 @@ bool xpdf_ImportFromFile( const ::rtl::OUString&        
                     rUR
             osl_writeFile( pIn, aBuf.getStr(), sal_uInt64(aBuf.getLength()), 
&nWritten );
         }
 
-        if( pOut && pErr )
+        // v1 backends put binary payloads on stderr and must alternate between
+        // the two pipes in lockstep; v2 backends inline them on stdout, which
+        // needs no such discipline and leaves stderr free for diagnostics.
+        // Only the handle differs -- the grammar is identical.
+        const oslFileHandle pBinary =
+            ( aBackend.eBinaryChannel == BINARY_ON_STDERR ) ? pErr : pOut;
+
+        if( pOut && pBinary )
         {
-            // read results of PDF parser. One line - one call to
-            // OutputDev. stderr is used for alternate streams, like
-            // embedded fonts and bitmaps
-            Parser aParser(rSink,pErr,xContext);
+            // read results of the PDF parser: one line, one ContentSink call
+            Parser aParser(rSink,pBinary,xContext);
             ::rtl::OStringBuffer line;
             while( osl_File_E_None == readLine(pOut, line) && line.getLength() 
)
                 aParser.parseLine(line.makeStringAndClear());
         }
     }
-    catch( uno::Exception& )
+    catch( const uno::Exception& rExc )
     {
         // crappy C file interface. need manual resource dealloc
+        const rtl::OString aMsg(
+            rtl::OUStringToOString( rExc.Message, RTL_TEXTENCODING_UTF8 ) );
+        fprintf( stderr, "pdfi: import aborted: %s\n", aMsg.getStr() );
         bRet = false;
     }
 
+    // Forward whatever the helper said on its stderr.  osl always redirects it
+    // into a pipe, so without this the backend's own diagnostics -- the one
+    // place a failing helper explains itself -- are swallowed entirely.  Read
+    // it only after stdout has ended, by which point the helper is done
+    // writing and this cannot deadlock against it.
+    if( pErr )
+    {
+        sal_Char  aBuf[1024];
+        sal_uInt64 nRead = 0;
+        while( osl_readFile( pErr, aBuf, sizeof(aBuf)-1, &nRead ) == 
osl_File_E_None
+               && nRead > 0 )
+        {
+            aBuf[nRead] = 0;
+            fprintf( stderr, "%s", aBuf );
+        }
+    }
+
     if( pIn )
         osl_closeFile(pIn);
     if( pOut )

Reply via email to