convert

package module
v0.17.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 22, 2026 License: BSD-3-Clause Imports: 32 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

convert

Pictures into a PDF, a PDF back into pictures or SVG, a PDF redrawn, and comic archives both ways. Pure Go, CGO-free, including GOOS=js.

pdfconv to-pdf       -dpi 300 -o scan.pdf page1.jpg page2.jpg logo.svg
pdfconv from-pdf     -dpi 150 -format png -pages 1,4-6 -o ./pages scan.pdf
pdfconv to-svg       -pages 1-3 -o ./svg scan.pdf       # scan_svg.zip; one page: scan.svg
pdfconv redraw       -greyscale -invert out.pdf grey.pdf
pdfconv redraw       -scanner -skew 0.6 clean.pdf looks-scanned.pdf
pdfconv from-archive book.cbz book.pdf
pdfconv to-archive   -title "Volume 3" book.pdf book.cbz
pdfconv bundle       send-these.zip a.pdf b.pdf c.pdf
pdfconv formats
pdf, err := convert.ToPDF(images, convert.Options{DPI: 300})
err = convert.WriteTo(f, images, convert.Options{DPI: 300, Page: pdfkit.A4})
pages, err := convert.FromPDF(pdf, convert.RasterOptions{DPI: 150, Format: "png"})
svgs, err := convert.PDFToSVG(pdf, convert.SVGOptions{Pages: []int{1, 2}})
err = convert.SVGArchive(w, svgs)                                    // page_1.svg, page_2.svg
out, err := convert.Redraw(pdf, convert.RedrawOptions{Greyscale: true})
pdf, err = convert.ArchiveToPDF(cbz, convert.Options{})
err = convert.ToArchive(w, pdf, convert.RasterOptions{DPI: 150})
pdf, err = convert.SVGToPDF(drawing, convert.Options{DPI: 72})       // vector, or drawn
pdf, err = convert.SVGToPDFVector(drawing, convert.Options{})        // vector or nothing

to-svg: a PDF page as SVG

pdfconv to-svg [-pages 1,3,5-9] [-password-file f] [-o dir] in.pdf

⛔ Passwords never go on the command line. -password is gone from every verb (to-svg, from-pdf, to-archive, redraw): an argument is visible in ps and in the shell's history. -password-file <path> reads it from a file, -password-file - from standard input; one trailing newline is stripped. This is a breaking CLI change (a MINOR bump below v1).

Built on render.PageSVG: paths, clips, images and transparency groups become SVG elements, text becomes outlines (so the file needs no font), and what SVG 1.1 cannot say — tiling and shading patterns, soft masks — is drawn by the pixel renderer and embedded as an <image> where it falls. Nothing the PDF says is copied into the output as text, and render checks every document against an allowlist before handing it over.

Naming follows BentoPDF's "PDF to SVG": one page is name.svg, several are name_svg.zip holding page_N.svg. The shape follows the pages selected, so -pages 2 of a long file is a single name.svg. -pages is an addition: BentoPDF offers no page selection. Not matched: BentoPDF also takes several PDFs at once into one pdf_to_svg.zip; here one PDF is one run.

⛔ All or nothing, as from-pdf and to-archive are. The first page that cannot be written stops the run, the error leads with the page number (in.pdf: page 4: its clips nest deeper than an SVG can hold), the exit status is 1, and no file is left behind — a zip with page 4 of 9 missing opens, counts and looks complete. Two refusals are expected on real files and stay reachable through errors.Is: render.ErrSVGTooDeep (clips nested past 64; render#143 tracks a raster fallback) and render.ErrTimedOut (ten seconds a page).

The input is untrusted, and everything is bounded before it is spent:

bound value where
pages in one run 1000 (convert.MaxSVGPages) before the first page is drawn, and before the list of pages is built; choose with -pages
SVG of one page 64 MiB (convert.DefaultSVGPageBytes) the smaller of this and what the run has left, handed to render, so it is refused rather than built and then found large
SVG of the whole run, hence the zip 256 MiB (convert.MaxSVGBytes) counted as each page is written
time for the whole run 5 min (convert.MaxSVGRunTime) checked between pages
time for one page 10 s (convert.DefaultSVGPageTime) the smaller of this and what the run has left

Memory is one page, not the run. The pages are streamed (convert.StreamSVG, convert.NewSVGArchive) into a temporary file in the output directory; the peak heap while 254 MiB of SVG went through was 41 MiB. PDFToSVG keeps every page in memory, up to 256 MiB, and is for callers that want them in memory. A page refused at its limit can still cost a large heap, driven by render parsing the content stream, not by the size of the SVG.

⛔ The time limit is a request, not a promise, while render#142 is open: render's deadline is only checked now and then, and one page has been seen to overrun it about seventy times. The run's time is checked between pages, so it inherits that overrun within a page.

The file is never written through a link or over a file: the output is made under a temporary name, then given its name with a hard link, which refuses a name that exists (a file, a directory, a symlink, even a dangling one); where hard links are not available, an exclusive create does the same. A refusal leaves nothing behind.

Zip entry names are built from the page number and nothing else; no byte of the PDF reaches one. A page number given twice is refused, by the API as by the command.

Against MuPDF

Allocations, exact, page 1 of three files (GOMAXPROCS=1): a 292 KB SVG took 26 749 allocations and 11.2 MB; a 40 KB one 105 542 and 86.9 MB; a 6 KB one 5 836 and 8.8 MB. Timing against mutool draw -F svg was deferred: the machine's one-minute load was 34 when it was measured, and a time taken there is not a time.

⛔ page10 comes after page2

A comic archive names its pages and nothing else records the order. Sorted as bytes, page10.png comes before page2.png, so a hundred-page book reads 1, 10, 11, … 2, 20, … — and nothing says so: every page is present, the count is right, and the file opens.

The ordering is natural: a run of digits compares as a number, without being parsed, so a page numbered past what an int holds still sorts. It is case-insensitive, because an archive mixes Page01 and page02 and a case-sensitive sort reads the book in two halves.

Going the other way, page names are zero-padded to the width of the last page number, not to a fixed four: padded too narrowly, a thousand-page document reads 1, 10, 100, 1000, 101 in every reader that sorts by name — which is every reader of this format.

What an archiver added — __MACOSX/, .DS_Store, ComicInfo.xml, a thumbnail — is skipped rather than refused. Real archives all carry some; refusing them would refuse most real files, and counting them puts rubbish in the middle of the book.

Going out, a ComicInfo.xml goes in first. It is what Komga, Kavita and Calibre read to know what a book is called and how many pages it has; without it a reader shows an untitled pile and has to open every entry to count it. The title is escaped — it comes from a caller by way of a filename, and an ampersand in it would otherwise produce metadata no reader can parse, which is worse than none because it looks like metadata.

What is not here

⛔ CBR is not read. A .cbr is a RAR archive, and this package reads ZIP only. go-filesystems/rar is the fleet's pure-Go RAR reader if that is wanted; it is left out here because it pulls a decoder and two modules in for one format variant.

bundle is the other half of what a reader might expect from "PDF to ZIP": it packs whole files, unchanged. Several PDFs that have to travel together are a packaging problem, not a conversion one. It is written to a temporary beside the target and renamed, so a failure leaves nothing under the final name — a half-written ZIP has its directory missing from the end, so it does not even open, but it is there and dated and somebody will try to send it.

SVG stays VECTOR where it can

An SVG handed to to-pdf is recognised by its content and its outlines become PDF path operators — so the result scales without pixels, and a figure that would be tens of kilobytes of raster is about a kilobyte of geometry.

⛔ What makes that safe is the refusal, not the translation. A converter between two vector languages that silently drops what it does not understand produces a file that opens and is quietly wrong, which is worse than a picture. go-gfx/gfx/svg's Walk reports every feature it could not hand over — a gradient, a clip path, an embedded raster — and a document that uses one is drawn whole at the chosen DPI instead. There is no third outcome where some of it survived.

This page used to say "SVG is DRAWN, not translated", and the reasoning it gave still holds: turning one vector language into another means reimplementing a renderer's worth of semantics, and half a translation is worse than none. What changed is that half became a condition this package can test for rather than a risk it could only avoid by never trying.

Measured: our renderer's picture of the vector page against go-gfx's own drawing of the same SVG differs by a mean of 0.03 of 255 per channel — and a blank page of the same size scores 38.19, so the measure can tell drawing from nothing. qpdf --check, mutool info and ghostscript all accept the output.

-dpi is consulted only when the document is drawn. On the vector path it has nothing to say, because the output has no resolution.

The pixel ceiling is passed through to go-gfx/gfx/svg: an SVG is the kind of thing people accept from strangers, and its own width and height decide an allocation — a hundred bytes declaring width="40000" cost 6.1 GiB before that was bounded.

Why it is small

Both ends were already here. go-pdfkit/pdfkit writes a PDF and can place an image on a page; go-pdfkit/render draws a page into a raster; go-images/images already had Invert, Grayscale, AdjustBrightness, AdjustContrast and Rotate. What was missing was the join — so this is wiring and codecs, not a new engine.

redraw RASTERISES, and says so everywhere

⛔ What comes out has no text in it: no selection, no search, no copy, no screen reader, and a much larger file. That is not a shortcoming — changing the colours a page is painted in means painting it — but it is a thing a caller has to have decided on purpose, which is why the verb is named for what it does rather than for what it is for.

Rotating, cropping, stamping and reordering keep the text. Those live in go-pdfkit/ops, not here, and redraw with no change asked for says so on stderr before it does anything.

-greyscale drop the colour
-invert turn light into dark
-brightness −1 (black) to 1 (white)
-contrast 1 leaves it, 2 doubles it, 0.5 halves it
-background #rgb, #rrggbb or #rrggbbaa, painted by the renderer
-scanner skew, grain and a worn lamp

The order of the transforms is written down rather than left to chance: colour, then tone, then the scanner's damage last. Greyscale after a contrast change is not the same picture as contrast after greyscale, and a caller who sets both would otherwise be guessing.

The scanner's grain is reproducible: a zero Seed is a fixed seed, not a random one, because two runs over the same file must produce the same bytes or nothing downstream can be compared, cached or checksummed. ⛔ The page index is mixed into it, or every page of a document gets identical grain — the one thing a scanner never does.

Two defects this found, both invisible to a byte count
-background painted nothing it was composited under the finished raster, and the renderer had already filled the page with opaque white. The option was documented, shipped and inert.
-brightness changed nothing images.AdjustBrightness adds its delta in channel units, 0–255, not in the −1..1 this option is documented in. A brightness of 0.4 added 0.4 of a level out of 255.

Both were found by tests that read pixels. The page count, the byte count and the exit status were right throughout.

Formats

read PNG, JPEG, GIF (standard library); BMP, TIFF, WebP (golang.org/x/image); PSD (go-images/psd)
write PNG, JPEG, GIF, BMP, TIFF, WebP (go-images/webp)

⛔ For WebP, quality 100 means the LOSSLESS codec, not the finest lossy one. They are two different codecs — VP8L is always exact, VP8 never is — and which wins depends entirely on the page:

a 160×160 detailed page a flat swatch
lossless 10 586 B, lossy at 50: 886 B lossless 102 B, lossy at 50: 176 B

A VP8 frame carries a fixed header — 1 056 bits of "every coefficient probability is unchanged" alone — that a nearly empty picture can never pay back. So the knob has to reach both codecs, and the only honest place for the boundary is the end of the range. A test reads the container's FourCC (VP8L against VP8 , with its trailing space) rather than looking at the picture, because a high-quality lossy page looks like the original too.

⛔ A format that can be read and not written is refused BY NAME. PSD is the one in that position now: the flattened composite reads perfectly well, and writing a layered document is a different job. "I do not know that format" would be a lie, and writing a PNG under a .psd name would be worse than either. The two refusals are different sentences and a test asserts that neither reads like the other — a test that until recently said this about WebP, and had to be rewritten when the encoder arrived.

⛔ The content decides the format, never the name. A scanner writing JPEG into page.png is ordinary; a converter that believed the extension would hand the decoder the wrong reader, or refuse a file it can read.

What decides the page

A picture has pixels, a page has points, and only the DPI says which page a picture is:

pdfconv to-pdf -dpi 300 scan.jpg   # 2480x3508 comes out A4
pdfconv to-pdf -dpi 72  scan.jpg   # the same file comes out a metre tall

With no -page, each page is sized to its own picture — which is what a set of scans of different sizes needs, and why an empty page size is an instruction rather than a missing value. With -page a4 the picture is fitted inside the paper:

  • ⛔ one scale for both axes. Scaling them separately fills the page and stretches the picture, and a stretched scan is a defect nobody reports because the page looks full;
  • ⛔ only ever shrink. "Fit on this paper" is not "make it as large as this paper": a 32-pixel logo blown up to A4 is a poster nobody asked for;
  • centred, and a margin wider than the paper gives way rather than erasing the picture — the picture is the content, the margin is a preference.

What it refuses

no pictures an empty PDF is a file, and a caller who passed an empty slice sees one and believes it worked
a picture past MaxPixels the size is decided by the input; the default ceiling is a hundred megapixels
-margin with no -page a page sized to its picture has no room to leave, and ignoring it lets somebody believe their pages have one
a page number past the end and it says how many there are
a PDF that opens and holds no pages said out loud, because an empty result otherwise reads like a selection that matched nothing

A page that cannot be written stops the run: a directory that looks like a complete conversion and is one page short is not something anybody checks. For the same reason the output directory is created after the conversion succeeds, so a failure leaves nothing behind that could be mistaken for "no pages".

Checks

100 % statement coverage on both packages, go vet and gofmt clean, and builds for nine targets including js/wasm, linux/loong64 and linux/s390x.

The end-to-end witness is a picture, not a number: a four-quadrant swatch goes in, comes back through a real rasteriser, and each quadrant is sampled in its own corner — ⛔ a flat fill survives being drawn upside down, so the test has to be able to see an orientation it does not expect.

Licence

BSD-3-Clause.

Documentation

Overview

Package convert turns pictures into a PDF and a PDF back into pictures.

Everything either side of the PDF was already here: github.com/go-pdfkit/pdfkit writes one and can place an image on a page, and github.com/go-pdfkit/render draws a page into a raster. What was missing was the join — which is why this package is wiring and codecs rather than a new engine.

Formats

Reading: PNG, JPEG and GIF from the standard library; BMP, TIFF and WebP from golang.org/x/image. Writing: PNG, JPEG, GIF, BMP and TIFF.

⛔ There is no WebP ENCODER in pure Go, so FromPDF refuses "webp" by name instead of quietly writing something else. A converter that answers a request it did not carry out is worse than one that says no.

What decides the page

A picture has pixels and a DPI; a PDF page has points. ToPDF sizes each page to its picture at the DPI given, so a 300-dpi scan comes back the size of the paper it came off. Asking for a fixed page size instead fits the picture inside it, centred, never cropping and never stretching: see Options.Page.

Pure Go

CGO-free, including GOOS=js. No C anywhere in the chain.

Index

Constants

View Source
const (
	DefaultSVGPageBytes = 64 << 20
	DefaultSVGPageTime  = 10 * time.Second
)

DefaultSVGPageBytes and DefaultSVGPageTime are what ONE page may take when the options say nothing: render's own defaults, spelled here because the run's totals must never stand in for them.

View Source
const DefaultMaxPixels = 100_000_000

DefaultMaxPixels is how large a picture Decode will read when no ceiling is given. A hundred megapixels is A4 at a thousand dots to the inch.

⛔ Said in bytes, because "a hundred megapixels" does not tell anybody what it permits: a decoded picture is four bytes a pixel, so this default lets a file of a few dozen bytes cost FOUR HUNDRED MEGABYTES. That is bounded, which is the property that matters and the one this package did not have — but a service taking pictures from strangers should set Options.MaxPixels to what its own pages actually need rather than inherit this.

Variables

View Source
var (
	// MaxArchiveEntries is how many files an archive may hold.
	//
	// It bounds an allocation made before anything is read, the same way
	// go-odf/odf's does: a ZIP's central directory costs about forty-six bytes
	// an entry, so a small file can declare a great many.
	MaxArchiveEntries = 4096

	// MaxArchiveEntryBytes is how large any one entry may be once opened, and
	// MaxArchiveBytes how much the whole archive may come to. One entry under
	// the ceiling says nothing about a thousand of them.
	MaxArchiveEntryBytes uint64 = 128 << 20
	MaxArchiveBytes      uint64 = 512 << 20
)

An archive of pictures is what a comic book is: a ZIP whose entries are the pages, in the order their NAMES put them. CBZ, CBR's zipped cousin, and "here are the scans in a zip" are all the same thing. ⛔ Variables rather than constants, and that is not a style choice: a ceiling of half a gigabyte cannot be reached by a test that has to run in a second, so a constant here would be a guard nobody could exercise — and this package has already shipped two of those. A test lowers them; nothing else should.

View Source
var (
	// MaxSVGPages is how many pages one run may write. A PDF can declare any
	// number of them, and every one costs up to ten seconds and 64 MiB of
	// interpreter, so the count is refused BEFORE the first page is drawn and the
	// message names -pages as the way to take fewer.
	MaxSVGPages = 1000

	// MaxSVGBytes is how much SVG all the pages together may come to, and so
	// bounds the zip too: the archive holds exactly these bytes, deflated, and
	// deflate of text does not grow it past this. One page under render's own
	// limit says nothing about a thousand of them.
	MaxSVGBytes = 256 << 20

	// MaxSVGRunTime is how long the whole run may interpret pages. A page may
	// take MaxDuration, which bounds one page; this bounds the sum.
	MaxSVGRunTime = 5 * time.Minute
)

⛔ Variables, for the reason the archive ceilings are: a limit no test can reach is a claim. A test lowers them; nothing else should.

View Source
var ErrNotXPS = errors.New("convert: this is not an OpenXPS package")

ErrNotXPS is returned for a file that is not an OpenXPS package at all, as opposed to one this cannot draw everything in.

View Source
var ErrSVGNotVector = errors.New("convert: this SVG cannot be drawn as paths")

ErrSVGNotVector says the document uses something the vector path cannot express, and names it. SVGToPDF answers this by rasterising.

Functions

func ArchiveToPDF added in v0.4.0

func ArchiveToPDF(src []byte, opt Options) ([]byte, error)

ArchiveToPDF lays the pictures in a ZIP onto pages, in the order their names put them.

⛔ The ORDER is the whole job. A comic archive names its pages and nothing else records the sequence, so "page10.jpg" has to follow "page2.jpg" — which a byte-wise sort does not do, and which is the single defect every naive reader of this format has. See naturalLess.

Entries that are not pictures are skipped rather than refused: real archives carry a ComicInfo.xml, a thumbnail, a __MACOSX folder, a readme.

func Bundle added in v0.4.0

func Bundle(w io.Writer, files map[string][]byte) error

Bundle packs whole files into a ZIP, unchanged.

⛔ It converts NOTHING, and that is the point: it is the one tool here whose job is to leave its input alone. Several PDFs that have to travel together — a submission, a set of invoices, a chapter each — are a packaging problem, not a conversion one, and running them through a renderer to put them in a zip would lose every byte of what made them worth sending.

The names are the ones given, with their directories stripped: an archive whose entries are absolute paths from somebody's disk tells a stranger where the files lived.

func Decode

func Decode(r io.Reader) (image.Image, string, error)

Decode reads a picture and says what format it turned out to be.

⛔ It reads the CONTENT. A file's name is a claim its bytes do not have to honour: a scanner that writes JPEG into "page.png" is ordinary, and a converter that believed the extension would hand the encoder the wrong picture or refuse a file it can read perfectly well. It refuses a picture of more than DefaultMaxPixels pixels, and it refuses it by its HEADER — see decodeWithin for why that distinction is the guard.

func DecodeBytes

func DecodeBytes(b []byte) (image.Image, string, error)

DecodeBytes is Decode over a slice.

func Encoders

func Encoders() []string

Encoders names every format FromPDF can write, in a stable order.

func LooksLikeSVG added in v0.4.0

func LooksLikeSVG(b []byte) bool

LooksLikeSVG says whether these bytes are an SVG document.

⛔ By their CONTENT, like every other format this package reads. It is more than a prefix test because an SVG legitimately begins with an XML declaration, a doctype, a comment or a byte-order mark, and a file that opens with any of those is still an SVG — refusing it for want of a "<svg" in the first four bytes would refuse most of what Inkscape writes.

func PageSizes

func PageSizes() []string

PageSizes names every paper size this package knows, in a stable order.

func ParsePageSize

func ParsePageSize(s string) (pdfkit.PageSize, error)

ParsePageSize reads a paper size: a name such as "a4", optionally with "-landscape", or "WIDTHxHEIGHT" in points.

⛔ "" is NOT an error and NOT a default size: it means "size each page to its own picture", which is a different instruction from "use A4". A set of scans of different sizes must not all be forced onto one paper because the caller said nothing.

func RasterizeSVG added in v0.4.0

func RasterizeSVG(doc []byte, opt Options) (image.Image, error)

RasterizeSVG draws an SVG and hands back the picture.

func Readers added in v0.14.0

func Readers() []string

Readers names every format this package can READ, in a stable order.

⛔ It exists because that list was TYPED OUT in cmd/pdfconv beside the registry it describes — "png, jpeg, gif, bmp, tiff, webp" — and a list typed beside the thing it describes is right the day it is typed and has no way of staying right: adding PSD here would have left the command line saying six formats while seven worked. image.Decode's registry cannot be enumerated, so one list is unavoidable; what is avoidable is two.

func ReadersToPDF

func ReadersToPDF(rs []io.Reader, opt Options) ([]byte, error)

ReadersToPDF decodes each reader and lays the pictures out as ToPDF does. The format of each is decided by its CONTENT, never by a name.

func Redraw added in v0.3.0

func Redraw(pdf []byte, opt RedrawOptions) ([]byte, error)

Redraw draws every page, changes the pixels, and lays the results back into a new PDF.

⛔ IT RASTERISES. What comes out has no text in it: no selection, no search, no copy, no screen reader, and a file many times larger. That is not a shortcoming of this implementation — changing the colours a page is PAINTED in means painting it — but it is a thing a caller has to have decided on purpose, which is why the function is named for what it does rather than for what it is for.

Where the operation can be done without redrawing, it belongs somewhere else: rotating, cropping, stamping and reordering are github.com/go-pdfkit/ops, and they keep the text.

func SVGArchive added in v0.17.0

func SVGArchive(w io.Writer, ps []SVGPage) error

SVGArchive writes the pages into a ZIP as page_N.svg.

func SVGEntryName added in v0.17.0

func SVGEntryName(n int) string

SVGEntryName is the name of a page inside the archive. It is built from the page NUMBER and nothing else: no byte of the PDF reaches an entry name, so a file cannot ask for "../../x" or an absolute path in an unzipper. Not padded, as BentoPDF's is not.

func SVGToPDF added in v0.4.0

func SVGToPDF(doc []byte, opt Options) ([]byte, error)

SVGToPDF puts an SVG document on a page, KEEPING IT VECTOR where it can.

The outlines become PDF path operators, so the result scales without pixels. When the document uses something the translation cannot express — a gradient, a clip path, an embedded raster — the whole document is DRAWN instead, at Options.DPI.

⛔ IT USED TO RASTERISE ALWAYS, and the reason it stopped is worth keeping. The old comment here said that turning one vector language into another "means reimplementing a renderer's worth of semantics, and a half-done translation produces a file that opens and is quietly wrong". That is still true, and it is exactly what the fallback is for. What changed is that go-gfx's svg.Walk now REPORTS the semantics it could not hand over, so "half-done" became a condition this package can test for rather than a risk it could only avoid by never trying. A document is translated whole or drawn whole; there is no third outcome in which some of it survived.

Options.DPI is consulted only on the drawing path, where it is the resolution: at 72 one SVG user unit is one point. On the vector path it has nothing to say, because the output has no resolution.

func SVGToPDFVector added in v0.16.0

func SVGToPDFVector(doc []byte, opt Options) ([]byte, error)

SVGToPDFVector lays an SVG on a page as paths, keeping it vector.

The page is the document's own size in points: one SVG user unit is one point, which is what a viewer calls 100%. Options.DPI is not consulted and has nothing to say here — a resolution is a property of a picture, and this output has none.

It returns an error wrapping ErrSVGNotVector for a document that uses a gradient, a clip path or an embedded image.

func StreamSVG added in v0.17.0

func StreamSVG(pdf []byte, opt SVGOptions, emit func(page, of int, svg []byte) error) error

StreamSVG draws the selected pages one at a time and hands each to emit with its number and how many pages were selected, in the order given. Its peak memory is ONE page's SVG and what drawing it takes, whatever the page count; emit owns the slice and may keep it.

⛔ If emit returns an error the run stops with it, unwrapped. A caller that writes the pages must therefore treat any error as "discard what was written": the policy is all or nothing, like PDFToSVG.

⛔ The run's time is checked BETWEEN pages and handed to each page as its limit, so a single page inherits whatever render's deadline does: while go-pdfkit/render#142 is open that deadline can be overrun many times within one page, and the ten seconds a page gets here are a request, not a promise.

The policy is the one FromPDF has: the first page that cannot be written stops the run, the error NAMES the page, and nothing is returned. A zip with page 4 of 9 missing opens, counts and looks complete, which is the worst shape a failure can take. Both render.ErrSVGTooDeep (issue render#143 tracks a raster fallback) and render.ErrTimedOut stay reachable through errors.Is.

The input is untrusted. Everything is bounded before it is spent: the page count before the first page, each page's output by render, the total by MaxSVGBytes (handed to render as the page's limit, so it is never allocated and THEN found too large), and the time by MaxSVGRunTime.

func ToArchive added in v0.4.0

func ToArchive(w io.Writer, pdf []byte, opt RasterOptions, title string) error

ToArchive draws the pages and writes them into a ZIP: one picture per page, named so that they come back in order, with a ComicInfo.xml beside them.

⛔ The ComicInfo.xml is not decoration. It is what Komga, Kavita and Calibre read to know how many pages a book has and what it is called; without it a reader shows the archive as an untitled pile and has to open every entry to count it. A CBZ with no metadata is a CBZ a library will not shelve. The title, when given, goes into that metadata; it is the book's name, not a filename.

func ToPDF

func ToPDF(images []image.Image, opt Options) ([]byte, error)

ToPDF lays each picture on a page of its own, in the order given.

func WriteTo

func WriteTo(w io.Writer, images []image.Image, opt Options) error

WriteTo is ToPDF straight to a writer, so a conversion of a hundred scans does not hold the finished PDF in memory as well as the pictures.

Types

type Encoder

type Encoder func(w io.Writer, m image.Image, quality int) error

Encoder is a picture format this package can WRITE. Reading is still wider than writing — a PSD decodes and does not encode — so the two stay separate tables rather than one list with exceptions in it.

type Options

type Options struct {
	// DPI is how many pixels of the picture go to an inch of paper. Zero means
	// 72, at which one pixel is one point and a picture comes out at the size
	// a PDF viewer calls 100%.
	//
	// It is what turns pixels into a page: a 2480x3508 scan at 300 is A4, and
	// the same scan at 72 is a page a metre tall. There is no right answer this
	// package could pick for you, only a sane default.
	DPI float64

	// Page, when set, is the page size every picture is placed on, and the
	// picture is FITTED inside it: scaled down to fit if it is too big, centred
	// either way, never cropped and never stretched out of proportion.
	//
	// When it is the zero value each page is sized to its own picture, which is
	// what a set of scans of different sizes needs.
	Page pdfkit.PageSize

	// Margin is how much paper is left around a fitted picture, in points. It
	// is only consulted when Page is set, because a page sized to its picture
	// has no room to leave.
	Margin float64

	// Title goes in the document information dictionary.
	Title string

	// MaxPixels refuses a picture larger than this, so that a file cannot
	// decide how much memory this package uses. Zero means a hundred million,
	// which is A4 at a thousand dots to the inch and well past any scanner.
	MaxPixels int
}

Options says how pictures become pages.

type Page

type Page struct {
	Number int    // one-based, as the file numbers it
	Format string // the format actually written
	Data   []byte
}

Page is one drawn page and the bytes it encoded to.

func FromPDF

func FromPDF(pdf []byte, opt RasterOptions) ([]Page, error)

FromPDF draws the pages of a PDF and encodes each one.

func FromPDFReader

func FromPDFReader(r io.Reader, opt RasterOptions) ([]Page, error)

FromPDFReader is FromPDF over a reader, for a file on disk.

type RasterOptions

type RasterOptions struct {
	// DPI is dots per inch. Zero means 150, which is legible on a screen and
	// not so large that a hundred-page file fills a disk.
	DPI float64

	// Pages selects which pages to draw, one-based, in the order given. Nil
	// means every page in the file's own order.
	Pages []int

	// Format is what to encode as: png, jpeg, gif, bmp, tiff or webp. Empty
	// means png, which is lossless and what a page of text should be.
	Format string

	// Quality is 1 to 100, and zero means 85. JPEG and WebP read it; every
	// other format ignores it.
	//
	// ⛔ For WebP, 100 means the LOSSLESS codec rather than the finest lossy
	// one: the two are different codecs, and a page of text wants the one
	// that is exact.
	Quality int

	// Password opens an encrypted file.
	Password string

	// MaxPixels refuses a page that would come out larger than this. Zero
	// leaves it to the renderer, whose own default is a little over A4 at 600
	// dots to the inch.
	MaxPixels int
}

RasterOptions says how pages become pictures.

type RedrawOptions added in v0.3.0

type RedrawOptions struct {
	RasterOptions

	// Title goes in the new document's information dictionary.
	Title string

	// Greyscale drops the colour.
	Greyscale bool

	// Invert turns light into dark. It is what a reader wants at night, and
	// what a plotter wants of a dark-background figure.
	Invert bool

	// Brightness shifts every channel, from -1 (black) to +1 (white). Zero
	// leaves it alone.
	Brightness float64

	// Contrast multiplies the distance from mid-grey: 1 leaves it alone, 2
	// doubles it, 0.5 halves it. Zero means 1 — ⛔ a zero that meant "no
	// contrast at all" would turn every page into a flat grey rectangle for
	// every caller who set only the other fields.
	Contrast float64

	// Background is the colour the page is painted on. nil leaves the
	// renderer's own white.
	//
	// ⛔ It is handed to the RENDERER rather than composited afterwards, and
	// the difference is the whole option. A first version painted the colour
	// under the finished raster — which does nothing at all, because the
	// renderer has already filled the page with opaque white and there is no
	// transparency left to show through. The option was documented, shipped,
	// and had no effect; a screenshot found it, a byte count did not.
	Background *color.RGBA

	// Scanner, when set, makes the page look like it went through one.
	Scanner *ScannerEffect
}

RedrawOptions says what to do to the pixels. Everything is off by default: the zero value redraws the pages unchanged, which is `rasterize-pdf`.

type SVGArchiveWriter added in v0.17.0

type SVGArchiveWriter struct {
	// contains filtered or unexported fields
}

SVGArchiveWriter builds the ZIP a page at a time, so that the pages need not be held together: the peak is the page being added and the zip writer's state.

func NewSVGArchive added in v0.17.0

func NewSVGArchive(w io.Writer) *SVGArchiveWriter

NewSVGArchive starts a ZIP of page_N.svg entries on w.

func (*SVGArchiveWriter) Add added in v0.17.0

func (a *SVGArchiveWriter) Add(n int, data []byte) error

Add writes page n. It refuses a number already added (two entries of one name read differently in every unzipper) and a total above MaxSVGBytes, BEFORE writing anything of the page.

func (*SVGArchiveWriter) Close added in v0.17.0

func (a *SVGArchiveWriter) Close() error

Close finishes the archive. An archive with no page is refused: an empty one is not a set of pictures.

type SVGOptions added in v0.17.0

type SVGOptions struct {
	// Pages selects pages, one-based, in the order given. Nil means every page.
	// A page named twice is refused: the archive names its entries after the
	// page, and two entries of one name read differently in every unzipper.
	Pages []int

	// Password opens an encrypted file.
	Password string

	// MaxBytes bounds ONE page's SVG; zero is [DefaultSVGPageBytes], 64 MiB. A
	// page is never granted more than the run has left of [MaxSVGBytes], which
	// bounds the total whatever this says.
	MaxBytes int

	// MaxDuration bounds one page; zero is [DefaultSVGPageTime], ten seconds. A
	// page is never granted more than the run has left of [MaxSVGRunTime]. See
	// [StreamSVG] on what the limit is worth while render#142 is open.
	MaxDuration time.Duration

	// RasterScale is the pixels per point of what SVG cannot say as a shape; zero
	// is render's two.
	RasterScale float64
}

SVGOptions says which pages become SVG, and how much of the machine a file may use to get there.

type SVGPage added in v0.17.0

type SVGPage struct {
	Number int // one-based, as the file numbers it
	Data   []byte
}

SVGPage is one page written as SVG.

func PDFToSVG added in v0.17.0

func PDFToSVG(pdf []byte, opt SVGOptions) ([]SVGPage, error)

PDFToSVG writes the pages of a PDF as SVG, all or nothing, holding every page in memory: up to MaxSVGBytes of it. A caller that writes the pages somewhere should use StreamSVG, whose peak is one page.

type ScannerEffect added in v0.3.0

type ScannerEffect struct {
	// Skew is how far the sheet sits off square, in degrees. A tenth to a
	// degree is what a careless hand produces.
	Skew float64

	// Noise is how much grain, from 0 to 1.
	Noise float64

	// Fade lightens the page, as a worn lamp does, from 0 to 1.
	Fade float64

	// Seed makes the grain reproducible. ⛔ Zero means a FIXED seed, not a
	// random one: two runs over the same file must produce the same bytes, or
	// nothing downstream can be compared, cached or checksummed — and an
	// effect that is different every time is one nobody can test.
	Seed uint64
}

ScannerEffect is the small damage a flatbed does: the sheet is never quite straight, the lamp is never quite even, and the sensor adds grain.

type XPSReport added in v0.17.0

type XPSReport struct {
	// Pages is how many fixed pages were written.
	Pages int
	// Unsupported is the sorted, de-duplicated list of constructs skipped.
	Unsupported []string
}

XPSReport says what was converted and, as importantly, what was left out.

⛔ A CONVERTER THAT DROPS SOMETHING SILENTLY IS WORSE THAN ONE THAT REFUSES. Unsupported names every construct a page used that this does not draw, so a caller can tell "an empty page" from "a page whose every mark was a kind I skipped". It is a set of kinds, not a count of occurrences: the question it answers is what to implement next, not how busy the page was.

func XPSToPDF added in v0.17.0

func XPSToPDF(b []byte, opt Options) ([]byte, *XPSReport, error)

XPSToPDF lays an OpenXPS package on PDF pages as paths, keeping it vector.

It reads the fixed pages of ECMA-388 §10 — <FixedPage>, its <Canvas> grouping and its <Path> marks — and draws each path's abbreviated geometry (§11.2.3, parsed by vector.ParseData) with its solid fill and stroke.

What it does not draw, and says so

<Glyphs> (§12) needs the package's fonts and a glyph-indexed PDF font; <ImageBrush>, <VisualBrush> and the gradient brushes (§13) need either a decoded picture or a PDF shading. None of them are drawn. Every one that a page uses is named in XPSReport.Unsupported rather than passed over, so a thin result is legible as a thin result.

⚠ WHAT A CORPUS OF ONE PRODUCER CANNOT TELL YOU. Measured on XPS written by Ghostscript's xpswrite device, a three-page package held 25073 <Path> elements and NOT ONE <Glyphs>: that producer draws text as filled outlines. That says what Ghostscript writes, not what XPS files contain — a writer that keeps text as glyphs produces a document this would hand back nearly empty, with "Glyphs" in the report. Do not read the first number as the second.

Directories

Path Synopsis
cmd
pdfconv command
pdfconv turns pictures into a PDF and a PDF back into pictures.
pdfconv turns pictures into a PDF and a PDF back into pictures.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址