https://bugs.documentfoundation.org/show_bug.cgi?id=172478

Kingsley <[email protected]> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |[email protected]

--- Comment #1 from Kingsley <[email protected]> ---
Comment on attachment 207461
  --> https://bugs.documentfoundation.org/attachment.cgi?id=207461
python script to demonstrate print parameters are ignored when set with page
print settings

"""
Standalone N-up print reproduction script.

Usage (run under LibreOffice's Python, or a Python with the UNO bridge
available — e.g. /usr/lib/libreoffice/program/python3):

    python3 test_nup_print.py \\
        --file /path/to/document.odt \\
        --printer "My Printer" \\
        --pages-per-side 4 \\
        [--use-soffice-subprocess] \\
        [--uno-host 127.0.0.1] \\
        [--uno-port 2002]

Start soffice first:
    soffice --headless
--accept="socket,host=127.0.0.1,port=2002;urp;StarOffice.ServiceManager"

Or use the --use-soffice-subprocess option to have this script start soffice
for you (for testing only).
"""

import argparse
import sys
import os


def build_props(values: dict):
    from com.sun.star.beans import PropertyValue  # type: ignore

    props = []
    for name, value in values.items():
        pv = PropertyValue()
        pv.Name = name
        pv.Value = value
        props.append(pv)
    return tuple(props)


NUP_LAYOUT = {
    2: (1, 2),
    4: (2, 2),
    6: (2, 3),
    9: (3, 3),
    16: (4, 4),
}


def main():
    parser = argparse.ArgumentParser(description="N-up print reproduction
script")
    parser.add_argument(
        "--file", required=True, help="Absolute path to a Writer document"
    )
    parser.add_argument("--printer", required=True, help="Printer name")
    parser.add_argument(
        "--pages-per-side",
        type=int,
        default=4,
        help="Number of pages per printed side (default: 4)",
    )
    parser.add_argument("--uno-host", default="127.0.0.1")
    parser.add_argument("--uno-port", type=int, default=2002)
    parser.add_argument(
        "--use-soffice-subprocess",
        action="store_true",
        help="Use a subprocess to start soffice (for testing only)",
    )
    args = parser.parse_args()

    if args.use_soffice_subprocess:
        import subprocess
        import time

        print("Starting soffice subprocess …")
        soffice_proc = subprocess.Popen(
            [
                "soffice",
                "--headless",
               
f"--accept=socket,host={args.uno_host},port={args.uno_port};urp;StarOffice.ServiceManager",
            ]
        )
        time.sleep(5)  # wait for soffice to start

    def cleanup_soffice():
        if args.use_soffice_subprocess:
            print("Terminating soffice subprocess …")
            soffice_proc.terminate()
            try:
                soffice_proc.wait(timeout=5)
            except subprocess.TimeoutExpired:
                print("soffice subprocess did not terminate in time, killing
…")
                soffice_proc.kill()
                soffice_proc.wait()

    if not os.path.isfile(args.file):
        print(f"ERROR: file not found: {args.file}", file=sys.stderr)
        cleanup_soffice()
        return 1

    nup = args.pages_per_side
    rows, cols = NUP_LAYOUT.get(nup, (1, nup))
    print(f"N-up={nup}  →  PageRows={rows}, PageColumns={cols}")

    # ── Connect to soffice via UNO
────────────────────────────────────────────
    import uno  # type: ignore
    from com.sun.star.connection import NoConnectException  # type: ignore

    local_ctx = uno.getComponentContext()
    resolver = local_ctx.ServiceManager.createInstanceWithContext(
        "com.sun.star.bridge.UnoUrlResolver", local_ctx
    )
    url = (
        f"uno:socket,host={args.uno_host},port={args.uno_port}"
        ";urp;StarOffice.ComponentContext"
    )
    print(f"Connecting to soffice at {args.uno_host}:{args.uno_port} …")
    try:
        ctx = resolver.resolve(url)
    except NoConnectException as e:
        print(f"ERROR: could not connect to soffice: {e}", file=sys.stderr)
        print(
            "Start soffice with:\n"
            f"  soffice --headless "
            f'--accept="socket,host={args.uno_host},port={args.uno_port}'
            ';urp;StarOffice.ServiceManager"',
            file=sys.stderr,
        )
        cleanup_soffice()
        return 1

    desktop = ctx.ServiceManager.createInstanceWithContext(
        "com.sun.star.frame.Desktop", ctx
    )
    print("Connected.")

    # ── Load document
─────────────────────────────────────────────────────────
    file_url = uno.systemPathToFileUrl(os.path.abspath(args.file))
    print(f"Loading: {args.file}")
    doc = desktop.loadComponentFromURL(
        file_url,
        "_blank",
        0,
        build_props(
            {
                "Hidden": True,
                "ReadOnly": True,
                "MacroExecutionMode": 0,
                "UpdateDocMode": 0,
            }
        ),
    )
    if doc is None:
        print("ERROR: loadComponentFromURL returned None", file=sys.stderr)
        cleanup_soffice()
        return 1
    print(f"Loaded  implementation={doc.getImplementationName()}")

    # ── Configure printer
─────────────────────────────────────────────────────
    print(f"Setting printer: {args.printer}")
    doc.setPrinter(build_props({"Name": args.printer}))

    # ── N-up via XPagePrintable
───────────────────────────────────────────────
    print_opts = build_props({"Wait": True, "CopyCount": 1})

    print(f"Calling setPagePrintSettings(PageRows={rows}, PageColumns={cols})
…")
    try:
        doc.setPagePrintSettings(build_props({"PageRows": rows, "PageColumns":
cols}))
        print("setPagePrintSettings OK")
    except Exception as e:
        print(f"ERROR in setPagePrintSettings: {e}", file=sys.stderr)
        doc.close(True)
        cleanup_soffice()
        return 1

    print("Calling printPages() …")
    try:
        doc.printPages(print_opts)
        print("printPages OK — job submitted to spooler")
    except Exception as e:
        print(f"ERROR in printPages: {e}", file=sys.stderr)
        doc.close(True)
        cleanup_soffice()
        return 1

    doc.close(True)
    print("Done.")
    cleanup_soffice()
    return 0


if __name__ == "__main__":
    sys.exit(main())

-- 
You are receiving this mail because:
You are the assignee for the bug.

Reply via email to