pdf

package
v0.26.0 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: BSD-3-Clause, MIT Imports: 43 Imported by: 2 modules, 1 package

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.

Documentation

Overview

Package pdf is a port of the Rust crate krilla, from the base commit e3459d06 (D62). It writes PDF files. docs/STATUS.md names the last commit of krilla that it follows.

krilla is a high-level library that creates PDF files. It builds on the crate pdf-writer, which okage ports into internal/pdfwriter. It hides the details of PDF behind primitives such as fills, strokes, gradients, glyphs and images.

A program starts with a Document. The Document starts the pages, and each Page gives a surface to draw on. Document.Finish writes the file. The file is in memory until Finish, because the subset of a font needs every glyph of the document (D62):

d := pdf.NewDocument(pdf.WithPDFVersion(pdf.PDF17))
ps, _ := pdf.PageSettingsFromWH(200, 200)
page := d.StartPage(ps)
// Draw on the surface of the page.
page.Finish()
if err := d.Finish(w); err != nil {
	return err
}

The state of the port

Phases 14, 15 and 16 of "The PDF writer" in docs/PLAN.md are done. They port the document, the pages, the serializer, the surface, the graphics, the images, the text, the metadata, the outline and the links. D99 adds the XMP metadata, the custom XMP metadata, the embedded files and the validators of PDF/A. These files are ported: geom.rs, num.rs, util.rs, error.rs, data.rs, lib.rs, stream.rs, resource.rs, chunk_container.rs, serialize.rs, document.rs, page.rs, configure/ without the validator of PDF/UA, content.rs, surface.rs, graphics/ without graphics/separation.rs, text/ without the standard fonts, interchange/metadata/, interchange/embed.rs, interchange/outline.rs, interactive/action.rs, interactive/annotation.rs and interactive/destination.rs.

Each file of graphics/ is a file graphics_<name>.go, and the ICC profiles of krilla are in the folder icc. graphics/image/mod.rs and png.rs are graphics_image.go and graphics_image_png.go. graphics_image_decode.go reads the headers of the image files in place of the decoders of upstream. The section Text names the files of text/. metadata/mod.rs, embed.rs, outline.rs, destination.rs, action.rs and annotation.rs are metadata.go, embed.go, outline.go, destination.go, action.go and annotation.go, without the forms. The section XMP metadata names the other files of interchange/metadata/. Document.SetMetadata, Document.EmbedFile, Document.SetOutline, Document.RegisterNamedDestination and Page.AddAnnotation take them.

The file lib.rs of upstream holds the documentation of the crate, which is this comment. The file data.rs holds the type Data, a shared slice of bytes. A []byte does that work in Go, so it has no port.

pdf leaves out the tags of PDF/UA, the forms, the validator of PDF/UA, the separation colors and the pages of other PDF files (D62, D99).

How the port is built

Rust borrows the state of the document in each page and each surface, and it drops a page or a surface at the end of its scope. Go has neither, so the port does this:

  1. serializeContext is SerializeContext of upstream, and chunkContainer is ChunkContainer. A Page, a StreamBuilder and a surface hold pointers to both, as the borrows of upstream do.
  2. A method Finish runs the impl Drop of upstream. Document.StartPage and Document.Finish finish the page that is open. Page.Finish finishes the surface that is open, with the function in Page.finishSurface.
  3. A panic of krilla that a caller can cause becomes an error that wraps a sentinel error of the root package, such as ErrPDFInvalidBox (D21, D62). A call of a surface records its error in the serializeContext, and Document.Finish returns the first one. These are the errors of a surface, of the text, of the links and of the outline: - ErrPDFPushPop for a pop without a push, or a push without a pop. - ErrPDFInvalidClipPath for a clip path that a transform makes too large. - ErrPDFInvalidStroke for a stroke whose width is negative or NaN. - ErrPDFInvalidPath for a path to stroke whose coordinates, with the width of the stroke, have a magnitude above 2^60, when krilla computes the bbox of the stroke. The stroker of krilla can panic there (D66). - ErrPDFMixedColorSpaces for a gradient whose stops have colors with different numbers of components, such as RGB and CMYK (D66). - ErrPDFInvalidGradient for a gradient with a transform that cannot be inverted where krilla needs its inverse. - ErrPDFImage for an image that does not decode, or a nil image, and ErrPDFSixteenBitImage for an image of 16 bits in PDF 1.4. - ErrPDFDuplicateNamedDestination for a name with two different destinations, which krilla returns too. - ErrPDFInvalidDestination for a destination to a page that does not exist. - ErrPDFInvalidAnnotation for a link annotation with no target, with quadrilaterals that give no rectangle, or with a rectangle that does not flip into the coordinates of PDF. - ErrPDFInvalidGlyph for a glyph whose range is not a range of its text, or whose ID is above 65535 in a CID font. - ErrPDFFont for a font that Document.Finish cannot embed, which krilla returns too. Finish returns it only with WithSubsetFallback(false) (D80). - ErrPDFValidation for a document that the validator of WithArchivalValidator does not allow, and an *XMPError that wraps ErrPDFXMP for custom XMP metadata that is not valid, which krilla returns too (D99).
  4. The cache of the serializer keys each object with a hash. sipHash hashes a name of the type, then the value, as sip_hash of upstream hashes a type_id, then the value. stableHash128 gives the hash of upstream, byte for byte, for the values that go into the file, such as the ID of the document.

How a phase adds its files

Phases 14, 15 and 16 added their files by these rules, and a later phase follows them too:

  1. A type that krilla writes once for each value, such as a graphics state, a shading or a pattern, satisfies cacheable: the methods typeID, hash and serialize. A type that a content stream names as a resource also satisfies resourceable, with the method newResource that gives one of the types of resource.go, such as extGStateResource. The method hash writes the fields in the order of the derived Hash of upstream, with the methods of hasher, such as h.rect and h.transform for a Rect and a Transform. registerResourceable writes the object once and returns its resource. The test type testGraphicsState in resource_test.go is the pattern.
  2. The method serialize of an object writes into the chunk of its kind in chunkContainer: cc.nonStream.extGStates, colorSpaces, masks, shadingFunctions and patterns for the objects without a stream, and cc.streams.shadingFunctions, patterns, xObjects and iccProfiles for the streams. It makes the bytes of a stream with a filterStreamBuilder, such as newFilterStreamFromContentStream, and writes the filters with filterStream.writeFilters.
  3. A method of a type of an earlier file that needs a type of a later file goes in the later file, because a Go method can be in any file of its package. For example, surface.go holds Page.Surface, StreamBuilder.Surface, StreamBuilder.SurfaceWithBBox and Surface.StreamBuilder. graphics_color.go holds serializeContext.registerColorSpace and the type maybeDeviceColorSpace of serialize.rs. graphics_icc.go holds PDFVersion.rgbICC and PDFVersion.greyICC of configure/version.rs. A unit that needs another method of Validators adds it to validators, in its own file. configure_validate.go holds the methods of Validators.
  4. A surface gives its stream to the code that made it with a function, as the finish_fn of upstream. The number of marked content IDs of upstream is for the tags, so the function takes the stream only.

The images of graphics/image add their chunks to cc.streams.images, with the error of a decode. The text, the metadata, the outline and the links add their fields to chunkContainer and globalObjects, and their steps to serializeContext.finish and chunkContainer.finish. The annotations of interactive/annotation.rs satisfy the interface annotation of page.go, and Page.AddAnnotation appends them to Page.annotations.

XMP metadata

D99 ports the XMP metadata, the custom XMP metadata and the validators of PDF/A, which D62 left out. internal/xmpwriter, the port of the crate xmp-writer, writes the XMP metadata. As krilla does by default, pdf writes it for each document, and WithXMPMetadata(false) turns it off. A validator of PDF/A turns it on. The modules of src/interchange/metadata are metadata.go for mod.rs, and metadata_custom.go, metadata_extension_schema.go, metadata_predefined.go, metadata_relax_ng.go and metadata_xmp.go for custom.rs, extension_schema.rs, predefined.rs, relax_ng.rs and xmp.rs. The module xmp of upstream is public as krilla::metadata::xmp. Its types, such as Namespace, Schema, Property and Value, are in this package with their Rust names. internal/xmlwriter writes the RELAX NG schema of PDF/A-4f and PDF/A-4e.

WithArchivalValidator sets a validator of PDF/A, the type Archival of src/configure/validate.rs. The validator of PDF/UA, Accessibility::UA1, is left out, because it requires the tags of PDF/UA, which pdf does not have. For the same reason, a document with ArchivalA1A, ArchivalA2A or ArchivalA3A fails with the validation error MissingTagging. The list of the validation errors of ErrPDFValidation is not public (D99).

Text

Phase 16 ports these files of src/text: mod.rs, font.rs, cid.rs, group.rs, type3.rs, shape.rs and glyph/. Each file is a file text_<name>.go, such as text_cid.go and text_glyph_colr.go, and mod.rs is text.go. content.go holds the methods of contentBuilder for the text, and surface.go holds DrawGlyphs and DrawText.

A Font holds the bytes of a TrueType, OpenType or collection font, with the coordinates of its variations. Surface.DrawGlyphs draws the glyphs that the caller places, with the text of their clusters, which the ToUnicode maps and the ActualText spans hold (D62, question 27). Surface.DrawText shapes a text with typesetting/harfbuzz first. A glyph with outlines and no color data goes into the CID font of its font, which holds the subset of internal/subsetter. A glyph with COLR, sbix, CBDT or SVG data goes into a Type 3 font. internal/colr walks the paint graph of a COLR glyph (D32).

The port differs from krilla in these ways:

  1. skrifa reads the metrics, the outlines and the bitmap strikes of a font in upstream. The port reads them with typesetting and with the bytes of the tables, by the rules of skrifa 0.44 (D52, D62). The outlines take the order of skrifa, and for a CFF or CFF2 font, the rules of NopFilterSink of read-fonts.
  2. krilla returns None from Font::new for data that it cannot read. NewFont returns an error that wraps okage.ErrPDFInvalidFont. A font that is not TrueType or OpenType gives this error, and the caller draws its glyphs as paths (question 25). KrillaError::Font is okage.ErrPDFFont.
  3. krilla panics for a glyph whose range is not a range of the text, and for a glyph ID above 65535 in a CID font. DrawGlyphs then records okage.ErrPDFInvalidGlyph, which Document.Finish returns, and draws nothing. CheckGlyphs gives the same error before the call (D80).
  4. harfrust sets no language when it guesses the properties of a text, and typesetting takes the language of the locale. naiveShape sets no language, as harfrust does.
  5. typesetting computes the deltas of HVAR in float32, and skrifa in fixed point. At a location of a variable font that is not exact in F2Dot14, a width of the CID font can differ by 1 unit (D65).
  6. The standard fonts of PDF are left out. Only the forms of krilla use them, and the base port has no forms (D62).
  7. WithSVGGlyphs is the field render_svg_glyph_fn of SerializeSettings. Its default is nil, which draws no SVG glyph, as the default function of upstream does. pdfsvg.RenderGlyph draws the SVG glyphs, as render_svg_glyph of krilla-svg does.
  8. When the subset of a CID font fails, krilla returns an error. The port writes the font without its font program, and draws each run of the font as invisible text, with the text rendering mode 3, so that a reader can copy and search the text. Each glyph of the run follows the text object as a path, with the fill and the stroke of the text. text_fallback.go changes the content streams that show the font, and only them, so the other bytes of the file do not change. WithSubsetFallback(false) gives the error of krilla, and WithLogger takes the logger of the fallback (D80).
  9. krilla marks a use of a glyph whose text differs from the text of its first use with ActualText. For a TrueType CID font, the port gives that use a second CID, with its own entry in the ToUnicode map and a CIDToGIDMap stream. A glyph without text takes an empty ActualText, so that MuPDF gives no U+FFFD for it. The switch Krilla of internal/pdfcompat turns both off for the tests against krilla (D102).

The additions for ivy

Phase 18 adds what the PDF device of ivy needs and krilla does not have (D62 item 11, D68). The files pdf/ivy_*.go hold them:

  • Surface.PushGroup draws a transparency group with the flags I and K, and an opacity, a blend mode and a soft mask in one graphics state.
  • Mask.WithBackdrop and Mask.WithTransfer write the entries BC and TR of a soft mask.
  • The field Extend of LinearGradient and RadialGradient writes the entry Extend of the shading, for the decal spread mode of okage and the gradients of okage.NewRadialGradientExtend.
  • The paint MeshGradient is a shading of type 4.
  • Surface.FillStencil fills through a stencil of 8 bits. A stencil of 0 and 255 with a color is an image mask (D69).
  • Surface.PushStrokeAdjustment writes the entry SA.
  • Surface.PaintFromShader converts a shader of okage into a paint.
  • Surface.DrawRaster draws a part of a page with okage, and draws the pixmap as an image (D62 item 10).
  • A stitching function of more than 256 functions becomes a tree of stitching functions, because MuPDF 1.28 reads no more (D69).
  • NewImageFont makes a font whose glyphs are images that the caller adds with Font.AddImageGlyph, each a mask or an image with its advance. DrawGlyphs draws them into Type 3 fonts with their text. A mask glyph is a shape glyph with d1, which takes the fill of the text, and an image glyph is a color glyph with d0. The file pdf/ivy_type3.go holds them (D89).
  • The link target DestinationName names a named destination by its name alone. Document.Finish resolves the name after the last page, and leaves out a link to a name without a destination (D104).
  • Surface.DrawInvisibleGlyphs draws a run of glyphs with its text as invisible text, with the text rendering mode 3. A reader can search and copy the text, and the run paints nothing. The file pdf/ivy_text.go holds it (D106).

A change to a file of the port for them has a comment that starts with okage: and names D68, D69, D89 or D106. Each one keeps the bytes and the hashes of every input of krilla, except a stitching function of more than 256 functions. MuPDF does not read such a function (D69).

Index

Constants

View Source
const (
	// PDFVersionMin is PdfVersion::MIN. The minimum supported PDF version.
	PDFVersionMin = PDF14
	// PDFVersionMax is PdfVersion::MAX. The maximum supported PDF version.
	PDFVersionMax = PDF20
)

The limits of PDFVersion.

View Source
const (
	// NormalizedF32Zero is NormalizedF32::ZERO. A NormalizedF32 value
	// initialized with zero.
	NormalizedF32Zero = path.NormalizedF32Zero
	// NormalizedF32One is NormalizedF32::ONE. A NormalizedF32 value
	// initialized with one.
	NormalizedF32One = path.NormalizedF32One
)

The constants of NormalizedF32 in krilla src/num.rs.

Variables

This section is empty.

Functions

func CheckGlyphs added in v0.19.0

func CheckGlyphs(glyphs []Glyph, text string) error

CheckGlyphs is not in krilla. It checks the glyphs of a call of DrawGlyphs with text, where krilla panics (D80). It returns an error that wraps okage.ErrPDFInvalidGlyph for the first glyph whose range is not a range of the text, or does not start and end at the bounds of its characters, or whose ID is above 65535. DrawGlyphs runs the same check when outlined is false, and Document.Finish then returns the same error. A program calls CheckGlyphs before DrawGlyphs to draw such a run in another way.

Types

type Action added in v0.16.0

type Action interface {
	Target
	// contains filtered or unexported methods
}

Action is Action in krilla src/interactive/action.rs. A Rust enum with data becomes an interface with one type for each case: LinkAction and GotoAction. An Action is a Target, as the case Target::Action of upstream makes it.

A type of action.

type Annotation added in v0.16.0

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

Annotation is Annotation in krilla src/interactive/annotation.rs. It satisfies the interface annotation of page.go.

An annotation.

func AnnotationFromLink(annotation LinkAnnotation) Annotation

AnnotationFromLink is the impl From<LinkAnnotation> for Annotation in krilla src/interactive/annotation.rs. The annotation has no alt text.

func NewAnnotationLink(annotation LinkAnnotation, altText *string) Annotation

NewAnnotationLink is Annotation::new_link in krilla src/interactive/annotation.rs. A nil alt text is None.

Create a new link annotation with some alt text.

Note that the alt text might be required in some cases, for example when exporting to PDF/UA.

func (Annotation) WithLocation added in v0.16.0

func (a Annotation) WithLocation(location Location) Annotation

WithLocation is Annotation::with_location in krilla src/interactive/annotation.rs. A location of 0 is None.

Sets the location of the annotation.

type Archival added in v0.22.0

type Archival uint8

Archival is Archival in krilla src/configure/validate.rs. The zero value is no validator, so the constants start at 1. WithArchivalValidator sets it.

A PDF/A conformance level.

const (
	// ArchivalA1A is Archival::A1_A, the validator for the PDF/A-1a
	// standard. It requires the tags of PDF/A, which pdf does not have, so
	// each document with it fails with the validation error MissingTagging
	// (D99).
	ArchivalA1A Archival = iota + 1
	// ArchivalA1B is Archival::A1_B, the validator for the PDF/A-1b
	// standard.
	ArchivalA1B
	// ArchivalA2A is Archival::A2_A, the validator for the PDF/A-2a
	// standard. It requires the tags of PDF/A, which pdf does not have.
	ArchivalA2A
	// ArchivalA2B is Archival::A2_B, the validator for the PDF/A-2b
	// standard. You should only use fonts that are legally embeddable in a
	// file for unlimited, universal rendering.
	ArchivalA2B
	// ArchivalA2U is Archival::A2_U, the validator for the PDF/A-2u
	// standard. It has all requirements of PDF/A-2b.
	ArchivalA2U
	// ArchivalA3A is Archival::A3_A, the validator for the PDF/A-3a
	// standard. It requires the tags of PDF/A, which pdf does not have.
	ArchivalA3A
	// ArchivalA3B is Archival::A3_B, the validator for the PDF/A-3b
	// standard. It has all requirements of PDF/A-2b.
	ArchivalA3B
	// ArchivalA3U is Archival::A3_U, the validator for the PDF/A-3u
	// standard. It has all requirements of PDF/A-2b.
	ArchivalA3U
	// ArchivalA4 is Archival::A4, the validator for the PDF/A-4 standard.
	// While not required, it's recommended to enable tagging.
	ArchivalA4
	// ArchivalA4F is Archival::A4F, the validator for the PDF/A-4f
	// standard. It has all requirements of PDF/A-4.
	ArchivalA4F
	// ArchivalA4E is Archival::A4E, the validator for the PDF/A-4e
	// standard. It has all requirements of PDF/A-4.
	ArchivalA4E
)

The values of Archival.

func (Archival) String added in v0.22.0

func (a Archival) String() string

String is Archival::as_str in krilla src/configure/validate.rs. A value that is not one of the constants gives Archival(n).

Returns a human-readable string representation of the conformance level.

type AssociationKind added in v0.22.0

type AssociationKind uint8

AssociationKind is AssociationKind in krilla src/interchange/embed.rs.

How an embedded file relates to the PDF document it is embedded in.

const (
	// AssociationKindSource means that the PDF document was created from
	// this source file.
	AssociationKindSource AssociationKind = iota
	// AssociationKindData means that this file was used to derive a visual
	// presentation in the PDF.
	AssociationKindData
	// AssociationKindAlternative is an alternative representation of this
	// document.
	AssociationKindAlternative
	// AssociationKindSupplement is additional resources for this document.
	AssociationKindSupplement
	// AssociationKindSchema is a machine-readable schema. PDF 2.0+, written
	// as AssociationKindUnspecified in earlier versions.
	AssociationKindSchema
	// AssociationKindUnspecified means that there is no clear relationship
	// or it is not known.
	AssociationKindUnspecified
)

The values of AssociationKind.

type BlendMode

type BlendMode uint8

BlendMode is BlendMode in krilla src/graphics/blend.rs. The zero value is BlendModeNormal.

How to blend source and backdrop.

const (
	BlendModeNormal BlendMode = iota
	BlendModeMultiply
	BlendModeScreen
	BlendModeOverlay
	BlendModeDarken
	BlendModeLighten
	BlendModeColorDodge
	BlendModeColorBurn
	BlendModeHardLight
	BlendModeSoftLight
	BlendModeDifference
	BlendModeExclusion
	BlendModeHue
	BlendModeSaturation
	BlendModeColor
	BlendModeLuminosity
)

The values of BlendMode.

type Category added in v0.22.0

type Category uint8

Category is Category in krilla src/interchange/metadata/xmp.rs.

Whether a property is generated internally or supplied externally.

const (
	// CategoryInternal means that the property is computed by the producer
	// (e.g. page count).
	CategoryInternal Category = iota
	// CategoryExternal means that the property is supplied by the user.
	CategoryExternal
)

The values of Category.

type Color

type Color interface {
	Paint
	// contains filtered or unexported methods
}

Color is Color in krilla src/graphics/color.rs. Upstream holds a regular color, which is a RegularColor, or a special color, which is a SpecialColor. The only special color is the separation color, which the base port leaves out (D62). So Color is RegularColor too, and its types are ColorRGB, ColorLuma and ColorCMYK. Color::to_regular gives the color itself, so it has no port.

A Color is a Paint, as the impl From<Color> for Paint of upstream makes it.

A wrapper for storing colors from different color spaces.

type ColorCMYK

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

ColorCMYK is cmyk::Color in krilla src/graphics/color.rs. The Default of upstream is DefaultColorCMYK, which is black.

A CMYK color.

func DefaultColorCMYK

func DefaultColorCMYK() ColorCMYK

DefaultColorCMYK is the Default of cmyk::Color in krilla src/graphics/color.rs: the black of the component black alone.

func NewColorCMYK

func NewColorCMYK(cyan, magenta, yellow, black uint8) ColorCMYK

NewColorCMYK is cmyk::Color::new in krilla src/graphics/color.rs.

Create a new CMYK color.

type ColorLuma

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

ColorLuma is luma::Color in krilla src/graphics/color.rs. The zero value is black, the Default of upstream.

A luma color.

func ColorLumaBlack

func ColorLumaBlack() ColorLuma

ColorLumaBlack is luma::Color::black in krilla src/graphics/color.rs.

Create a black luma color.

func ColorLumaWhite

func ColorLumaWhite() ColorLuma

ColorLumaWhite is luma::Color::white in krilla src/graphics/color.rs.

Create a white luma color.

func NewColorLuma

func NewColorLuma(lightness uint8) ColorLuma

NewColorLuma is luma::Color::new in krilla src/graphics/color.rs.

Create a new luma color.

type ColorRGB

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

ColorRGB is rgb::Color in krilla src/graphics/color.rs. The zero value is black, the Default of upstream.

An RGB color.

func ColorRGBBlack

func ColorRGBBlack() ColorRGB

ColorRGBBlack is rgb::Color::black in krilla src/graphics/color.rs.

Create a black RGB color.

func ColorRGBWhite

func ColorRGBWhite() ColorRGB

ColorRGBWhite is rgb::Color::white in krilla src/graphics/color.rs.

Create a white RGB color.

func NewColorRGB

func NewColorRGB(red, green, blue uint8) ColorRGB

NewColorRGB is rgb::Color::new in krilla src/graphics/color.rs.

Create a new RGB color.

func NewColorRGBLinear

func NewColorRGBLinear(red, green, blue uint8) ColorRGB

NewColorRGBLinear is rgb::Color::new_linear in krilla src/graphics/color.rs. It gives the same color as NewColorRGB, as upstream does.

Create a new linear RGB color.

func (ColorRGB) Blue

func (c ColorRGB) Blue() uint8

Blue is rgb::Color::blue in krilla src/graphics/color.rs.

The blue component of the color.

func (ColorRGB) Green

func (c ColorRGB) Green() uint8

Green is rgb::Color::green in krilla src/graphics/color.rs.

The green component of the color.

func (ColorRGB) Red

func (c ColorRGB) Red() uint8

Red is rgb::Color::red in krilla src/graphics/color.rs.

The red component of the color.

type DateTime added in v0.16.0

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

DateTime is DateTime in krilla src/interchange/metadata/mod.rs. A field that is an Option of upstream has a flag for Some.

A datetime. Invalid values will be clamped.

func NewDateTime added in v0.16.0

func NewDateTime(year uint16) DateTime

NewDateTime is DateTime::new in krilla src/interchange/metadata/mod.rs.

Create a new, minimal date. The year will be clamped within the range 0-9999.

func (DateTime) Day added in v0.16.0

func (d DateTime) Day(day uint8) DateTime

Day is DateTime::day in krilla src/interchange/metadata/mod.rs.

Add the day field. It will be clamped within the range 1-31.

func (DateTime) Hour added in v0.16.0

func (d DateTime) Hour(hour uint8) DateTime

Hour is DateTime::hour in krilla src/interchange/metadata/mod.rs.

Add the hour field. It will be clamped within the range 0-23.

func (DateTime) Minute added in v0.16.0

func (d DateTime) Minute(minute uint8) DateTime

Minute is DateTime::minute in krilla src/interchange/metadata/mod.rs.

Add the minute field. It will be clamped within the range 0-59.

func (DateTime) Month added in v0.16.0

func (d DateTime) Month(month uint8) DateTime

Month is DateTime::month in krilla src/interchange/metadata/mod.rs.

Add the month field. It will be clamped within the range 1-12.

func (DateTime) Second added in v0.16.0

func (d DateTime) Second(second uint8) DateTime

Second is DateTime::second in krilla src/interchange/metadata/mod.rs.

Add the second field. It will be clamped within the range 0-59.

func (DateTime) UTCOffsetHour added in v0.16.0

func (d DateTime) UTCOffsetHour(hour int8) DateTime

UTCOffsetHour is DateTime::utc_offset_hour in krilla src/interchange/metadata/mod.rs.

Add the offset from UTC in hours. If not specified, the time will be assumed to be local to the viewer's time zone. It will be clamped within the range -23-23.

func (DateTime) UTCOffsetMinute added in v0.16.0

func (d DateTime) UTCOffsetMinute(minute uint8) DateTime

UTCOffsetMinute is DateTime::utc_offset_minute in krilla src/interchange/metadata/mod.rs.

Add the offset from UTC in minutes. This will have the same sign as set in UTCOffsetHour. It will be clamped within the range 0-59.

type Destination added in v0.16.0

type Destination interface {
	Target
	// contains filtered or unexported methods
}

Destination is Destination in krilla src/interactive/destination.rs. A Rust enum with data becomes an interface with one type for each case: XYZDestination and NamedDestination. The impl From of upstream for each type is the conversion of the type into the interface. A Destination is a Target, as the case Target::Destination of upstream makes it.

The type of destination.

type DestinationName added in v0.23.0

type DestinationName string

DestinationName is a target of a link annotation that names a named destination by its name alone. The annotation writes the name, and Document.Finish resolves it after the last page. So a page can link to a destination of a later page before that page is drawn. The caller registers the destination of the name before Document.Finish, with Document.RegisterNamedDestination or with a link to a NamedDestination. Document.Finish leaves out a link to a name that has no destination, and logs it to the logger of WithLogger. krilla has no such target (D104).

type Document

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

Document is Document in krilla src/document.rs.

A PDF document.

Creating PDFs always requires some kind of global state to keep track of different aspects in the creation process, meaning that it is not possible to generate multiple pages at the same time. Instead, you add pages one after the other with the method StartPage. Rust makes sure that a page is finished before the next one starts. Go cannot, so StartPage and Finish finish the page that is open.

The methods SetMetadata, SetOutline and RegisterNamedDestination are in metadata.go, outline.go and destination.go, and EmbedFile is in embed.go. pdf leaves out embed_pdf_pages, set_field_tree and set_tag_tree (D62).

func NewDocument

func NewDocument(opts ...Option) *Document

NewDocument is Document::new_with in krilla src/document.rs. The options are the fields of SerializeSettings, and no option gives the settings of Document::new.

Create a new document with custom serialize settings.

func (*Document) EmbedFile added in v0.22.0

func (d *Document) EmbedFile(file EmbeddedFile) bool

EmbedFile is Document::embed_file in krilla src/document.rs. It returns false where upstream returns None.

Embed a new file in the PDF document.

Returns false if the file couldn't be embedded because a file with the same name has already been embedded.

func (*Document) Finish

func (d *Document) Finish(w io.Writer) error

Finish is Document::finish in krilla src/document.rs. krilla returns the bytes of the file. The port writes them to w (D62). It finishes the page that is open first. A document without pages gets one empty page of the default settings, as in upstream. A second call returns ErrPDFFinished.

Attempt to export the document to a PDF file.

func (*Document) RegisterNamedDestination added in v0.16.0

func (d *Document) RegisterNamedDestination(dest NamedDestination) bool

RegisterNamedDestination is Document::register_named_destination in krilla src/document.rs. It returns false where upstream returns None.

Manually register a global named destination.

Named destinations used in link annotations are automatically registered, so you don't need to call this function for them.

Returns false if a named destination with the same name and a different destination has already been registered, and therefore could not be registered again.

func (*Document) ResetLocation

func (d *Document) ResetLocation()

ResetLocation is Document::reset_location in krilla src/document.rs.

Reset the location that should be assumed for subsequent operations.

func (*Document) SetLocation

func (d *Document) SetLocation(location Location)

SetLocation is Document::set_location in krilla src/document.rs.

Set the location that should be assumed for subsequent operations.

func (*Document) SetMetadata added in v0.16.0

func (d *Document) SetMetadata(metadata Metadata)

SetMetadata is Document::set_metadata in krilla src/document.rs.

Set the metadata of the document.

func (*Document) SetOutline added in v0.16.0

func (d *Document) SetOutline(outline Outline)

SetOutline is Document::set_outline in krilla src/document.rs.

Set the outline of the document.

func (*Document) StartPage

func (d *Document) StartPage(pageSettings PageSettings) *Page

StartPage is Document::start_page_with in krilla src/document.rs. It finishes the page that is open first. DefaultPageSettings gives the settings of Document::start_page. It panics after Finish, as Rust cannot call a method on a document that it has finished.

Start a new page with specific page settings.

type EmbeddedFile added in v0.22.0

type EmbeddedFile struct {
	// Path is the name of the embedded file.
	Path string
	// MIMEType is the mime type of the embedded file.
	MIMEType *MIMEType
	// Description is a description of the embedded file.
	Description *string
	// AssociationKind is the association kind of the embedded file.
	AssociationKind AssociationKind
	// Data is the raw data of the embedded file.
	Data []byte
	// ModificationDate is the modification date of the embedded file.
	ModificationDate *DateTime
	// Compress says whether the embedded file should be compressed
	// (recommended to turn off if the original file already has
	// compression). If nil, krilla will use its own logic for determining
	// whether to compress the file or not.
	Compress *bool
	// Location is the location of the embedded file. Zero is None.
	Location Location
}

EmbeddedFile is EmbeddedFile in krilla src/interchange/embed.rs. A field of upstream that is an Option is a pointer here, and nil is None.

An embedded file.

type ExtendMode added in v0.17.0

type ExtendMode uint8

ExtendMode says which ends of a linear or a radial gradient extend past the stops. It is the entry Extend of a shading of type 2 or 3. The zero value extends both ends, as krilla does. It is not in krilla (D68).

A linear gradient takes it only with SpreadMethodPad. Past an end that does not extend, the gradient paints nothing. This is the decal spread mode of okage (D55), and the rule of NewRadialGradientExtend of okage (D64).

const (
	// ExtendBoth extends both ends.
	ExtendBoth ExtendMode = iota
	// ExtendStart extends the start only.
	ExtendStart
	// ExtendEnd extends the end only.
	ExtendEnd
	// ExtendNone extends no end.
	ExtendNone
)

The values of ExtendMode.

type Fill

type Fill struct {
	// Paint is the paint of the fill.
	Paint Paint
	// Opacity is the opacity of the fill.
	Opacity NormalizedF32
	// Rule is the fill rule that should be used when applying the fill.
	Rule FillRule
}

Fill is Fill in krilla src/graphics/paint.rs. DefaultFill gives the Default of upstream. The derived Hash of upstream hashes no Fill, Stroke or StrokeDash in the cache of the serializer, so they have no method hash.

A fill.

func DefaultFill

func DefaultFill() Fill

DefaultFill is the impl Default for Fill in krilla src/graphics/paint.rs: an opaque black fill with the non-zero rule.

type FillRule

type FillRule uint8

FillRule is FillRule in krilla src/graphics/paint.rs. The zero value is FillRuleNonZero, the Default of upstream.

A fill rule.

const (
	// FillRuleNonZero is the non-zero fill rule.
	FillRuleNonZero FillRule = iota
	// FillRuleEvenOdd is the even-odd fill rule.
	FillRuleEvenOdd
)

The values of FillRule.

type Font added in v0.16.0

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

Font is Font in krilla src/text/font.rs. Two fonts are equal when their fontInfo is equal, as in upstream, so two fonts that NewFont makes from the same bytes share their subset in a document.

An OpenType font. Can be a TrueType, OpenType font or a TrueType collection. It holds a reference to the underlying data as well as some basic information about the font.

A Font is safe for concurrent use. Do not change the bytes that NewFont takes while the font is in use.

func NewFont added in v0.16.0

func NewFont(data []byte, index int, opts ...FontOption) (*Font, error)

NewFont is Font::new and Font::new_variable in krilla src/text/font.rs. The index indicates the index of a font in a TrueType collection, and is 0 for a single font. WithVariations gives the coordinates of a variable font.

krilla returns None if the index is invalid or the font cannot be read. The port returns an error that wraps okage.ErrPDFInvalidFont. A font that is not TrueType or OpenType, such as a Type 1 font or a bare CFF font, gives that error. The caller draws its glyphs as paths with Surface.DrawPath (D62, question 25). A WOFF, WOFF2 or EOT font is converted with the package webfont first.

Create a new font from some data.

func NewImageFont added in v0.22.0

func NewImageFont(unitsPerEm float32, opts ...ImageFontOption) (*Font, error)

NewImageFont returns a font whose glyphs are images that the caller gives with AddImageGlyph. unitsPerEm is the size of an em in the units of the glyphs. DrawGlyphs draws its glyphs into Type 3 fonts, with the text that a reader can copy or search. The font has no character map, so DrawText does not draw it. It is not in krilla (D89).

It returns an error that wraps okage.ErrPDFInvalidFont for a unitsPerEm that is not finite or not above 0.

func (*Font) AddImageGlyph added in v0.22.0

func (f *Font) AddImageGlyph(g ImageGlyph) (GlyphID, error)

AddImageGlyph adds a glyph to an image font, and returns its ID. The IDs count from 0, in the order of the calls. A program adds a glyph before it draws it, and can add glyphs until Document.Finish. The font copies the mask, and keeps the image. It is not in krilla (D89).

It returns an error that wraps okage.ErrPDFInvalidGlyph for a glyph with both or neither of Mask and Image, for an advance or a transform that is not finite, for a mask with a pixel that is not 0 or 255, and when the font already holds 65,536 glyphs. It returns an error that wraps okage.ErrPDFImage for a mask that is larger than the limit of Surface.FillStencil, and okage.ErrPDFInvalidFont for a font of NewFont.

func (*Font) String added in v0.19.0

func (f *Font) String() string

String is the impl Debug for Font in krilla src/text/font.rs. It satisfies the fmt.Stringer interface. It gives the PostScript name and the index of the font, as the Debug format of Rust writes them, such as Font { postscript_name: Some("NotoSans-Regular"), index: 0, .. }.

func (*Font) UnitsPerEm added in v0.16.0

func (f *Font) UnitsPerEm() float32

UnitsPerEm is Font::units_per_em in krilla src/text/font.rs.

The units per em of the font.

type FontOption added in v0.16.0

type FontOption func(*fontOptions)

FontOption is an option of NewFont (D20).

func WithVariations added in v0.16.0

func WithVariations(coords ...VariationCoord) FontOption

WithVariations is the argument variation_coords of Font::new_variable in krilla src/text/font.rs. It sets the coordinates of the variations of a variable font. A tag that is not an axis of the font has no effect.

type Glyph added in v0.16.0

type Glyph struct {
	// GlyphID is the glyph ID of the glyph.
	GlyphID GlyphID
	// TextRange is the range in the original text that corresponds to the
	// cluster of the glyph.
	TextRange TextRange
	// XAdvance is the advance of the glyph.
	XAdvance float32
	// XOffset is the x offset of the glyph.
	XOffset float32
	// YOffset is the y offset of the glyph.
	YOffset float32
	// YAdvance is the y advance of the glyph.
	YAdvance float32
	// Location is the location of the glyph. If set, the surface sets it
	// with SetLocation before it processes the glyph. Zero is None.
	Location Location
}

Glyph is KrillaGlyph in krilla src/text/glyph/mod.rs. Its methods are the methods of the trait Glyph of upstream for KrillaGlyph.

A glyph type that implements Glyph.

XAdvance, XOffset, YOffset and YAdvance need to be normalized, i.e. divided by the units per em!

type GlyphID added in v0.16.0

type GlyphID uint32

GlyphID is GlyphId in krilla src/text/glyph/mod.rs.

A glyph ID.

type GotoAction added in v0.16.0

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

GotoAction is the case Action::Goto in krilla src/interactive/action.rs.

A go-to action.

func NewGotoAction added in v0.16.0

func NewGotoAction(destination Destination) GotoAction

NewGotoAction makes the case Action::Goto in krilla src/interactive/action.rs. A nil destination makes Document.Finish return ErrPDFInvalidAnnotation.

type Graphic

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

Graphic is Graphic in krilla src/graphics/graphic.rs. Surface.DrawGraphic draws it.

A cacheable graphic. You can use this for large graphics objects which you want to reuse in multiple locations in the same document. Embedding the same graphic multiple times will ensure that it is only actually written once in the PDF document, which might lead to better file sizes.

IMPORTANT: Note that you must only use a graphic in the document that you created it with! If you use it in a different document, you will end up with an invalid PDF file.

func NewGraphic

func NewGraphic(stream *Stream, isolated bool) Graphic

NewGraphic is Graphic::new in krilla src/graphics/graphic.rs.

Create a new graphic. stream contains the content description of the graphic. isolated indicates whether the contents of the graphic should be isolated from wherever the graphic is invoked.

type Group added in v0.17.0

type Group struct {
	// Opacity is the opacity of the group, the entries CA and ca of its
	// graphics state.
	Opacity NormalizedF32
	// BlendMode is the blend mode of the group onto its backdrop.
	BlendMode BlendMode
	// Isolated starts the group on a transparent backdrop, the flag I of
	// the group. Without it, the content of the group blends with the
	// content under the group.
	Isolated bool
	// Knockout makes each object of the group draw over the backdrop of the
	// group, and not over the earlier objects of the group. This is the
	// flag K of the group (ISO 32000-2, 11.4.8).
	Knockout bool
	// Mask is the soft mask of the group, or nil.
	Mask *Mask
}

Group is a transparency group of PDF, which Surface.PushGroup starts. It is not in krilla (D68).

The zero Group draws its content at an opacity of 0. Set Opacity to NormalizedF32One for a group without transparency.

type ICCProfile

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

ICCProfile is ICCProfile<C> in krilla src/graphics/icc.rs. The constant C of upstream is the number of components of the color space of the profile. Go has no constant type parameter, so the profile holds the number. A *ICCProfile is cheap to share, as the Arc of upstream.

An ICC profile.

func NewICCProfile

func NewICCProfile(data []byte, components uint8) (*ICCProfile, bool)

NewICCProfile is ICCProfile::new in krilla src/graphics/icc.rs, with C in components. It deflates the data at once, as upstream does.

Create a new ICC profile.

Returns false if the metadata of the profile could not be read or if the number of channels of the underlying data does not correspond to components.

type Image added in v0.16.0

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

Image is Image in krilla src/graphics/image/mod.rs, with the fields of ImageRepr. A *Image is cheap to share, as the Arc of upstream. The Image keeps the data that made it, so the caller must not change the data.

A bitmap image.

func ImageFromGIF added in v0.16.0

func ImageFromGIF(data []byte, interpolate bool) (*Image, error)

ImageFromGIF is Image::from_gif in krilla src/graphics/image/mod.rs. It takes the first frame of the file.

Create a new bitmap image from a .gif file.

func ImageFromImage added in v0.16.0

func ImageFromImage(img image.Image, interpolate bool) (*Image, error)

ImageFromImage is Image::from_custom in krilla src/graphics/image/mod.rs, for an image.Image of Go in place of the trait CustomImage. A gray image becomes an image in the luma color space, a CMYK image an image in the CMYK color space, and any other image an RGB image. An image with 16 bits for each channel, such as an *image.NRGBA64, keeps its 16 bits. The image has an alpha channel when it is not opaque. It returns an error that wraps ErrPDFImage when the samples of the image, with an alpha channel, need more than maxImageBytes bytes.

Create a new image from a custom image.

func ImageFromJPEG added in v0.16.0

func ImageFromJPEG(data []byte, interpolate bool) (*Image, error)

ImageFromJPEG is Image::from_jpeg in krilla src/graphics/image/mod.rs. The PDF file holds the data of the file as it is.

Create a new bitmap image from a .jpg file.

func ImageFromPNG added in v0.16.0

func ImageFromPNG(data []byte, interpolate bool) (*Image, error)

ImageFromPNG is Image::from_png in krilla src/graphics/image/mod.rs. interpolate sets the key /Interpolate of the image.

Create a new bitmap image from a .png file.

If possible, the PNG image will be embedded directly into the PDF. Otherwise, krilla falls back to decoding and then re-compressing the image.

func ImageFromPNGNative added in v0.16.0

func ImageFromPNGNative(data []byte, interpolate bool) (*Image, error)

ImageFromPNGNative is Image::from_png_native in krilla src/graphics/image/mod.rs.

Create a new bitmap image from a .png file without decoding its pixels.

If possible, the PNG image will be embedded directly into the PDF. Otherwise, unlike ImageFromPNG, this function returns an error. This is useful if you do not want the image to be decoded without notice.

func ImageFromRGBA8 added in v0.16.0

func ImageFromRGBA8(data []byte, width, height uint32) *Image

ImageFromRGBA8 is Image::from_rgba8 in krilla src/graphics/image/mod.rs. data holds 4 bytes for each pixel, which are not premultiplied by the alpha. Like upstream, it does not check the length of data.

Create a new RGB image from raw RGBA pixels.

func ImageFromWebP added in v0.16.0

func ImageFromWebP(data []byte, interpolate bool) (*Image, error)

ImageFromWebP is Image::from_webp in krilla src/graphics/image/mod.rs. It takes the first frame of the file.

Create a new bitmap image from a .webp file.

func (*Image) Size added in v0.16.0

func (i *Image) Size() (width, height uint32)

Size is Image::size in krilla src/graphics/image/mod.rs.

Return the size of the image.

type ImageFontOption added in v0.22.0

type ImageFontOption func(*imageFontOptions)

ImageFontOption is an option of NewImageFont (D20).

func WithImageFontName added in v0.22.0

func WithImageFontName(name string) ImageFontOption

WithImageFontName sets the name of the Type 3 fonts of an image font in the file. The default is "unknown", as krilla names a font without a PostScript name. A name of more than 115 bytes is cut, as krilla cuts the name of a Type 3 font.

type ImageGlyph added in v0.22.0

type ImageGlyph struct {
	// Advance is the advance of the glyph, in the units of the font.
	Advance float32
	// Mask is a stencil of 0 and 255. A pixel of 255 takes the fill of the
	// text. The glyph is a shape glyph, with the operator d1. A mask with
	// no pixel draws nothing, as a space does.
	Mask *image.Alpha
	// Image is the image of a color glyph, with the operator d0. The glyph
	// keeps the colors of the image.
	Image *Image
	// Transform maps the pixels of the mask or of the image, with y down,
	// onto the units of the font, with y up. The pixel 0, 0 is the top left
	// corner of the image.
	Transform Transform
}

ImageGlyph is one glyph of an image font. Exactly one of Mask and Image is set.

type IntoValueType added in v0.22.0

type IntoValueType interface {
	// contains filtered or unexported methods
}

IntoValueType is the trait Into<ValueType> of krilla src/interchange/metadata/xmp.rs. ValueType, SimpleType, PredefinedStruct and StructType satisfy it.

type LangText added in v0.22.0

type LangText struct {
	Lang *string
	Text string
}

LangText is an entry of Value::LanguageAlternative in krilla src/interchange/metadata/xmp.rs: an optional RFC 3066 language tag and its text. A nil language is None, which krilla writes as x-default.

type LineCap

type LineCap uint8

LineCap is LineCap in krilla src/graphics/paint.rs. The zero value is LineCapButt, the Default of upstream.

A line cap.

const (
	// LineCapButt is the butt line cap.
	LineCapButt LineCap = iota
	// LineCapRound is the round line cap.
	LineCapRound
	// LineCapSquare is the square line cap.
	LineCapSquare
)

The values of LineCap.

type LineJoin

type LineJoin uint8

LineJoin is LineJoin in krilla src/graphics/paint.rs. The zero value is LineJoinMiter, the Default of upstream.

A line join.

const (
	// LineJoinMiter is the miter line join.
	LineJoinMiter LineJoin = iota
	// LineJoinRound is the round line join.
	LineJoinRound
	// LineJoinBevel is the bevel line join.
	LineJoinBevel
)

The values of LineJoin.

type LinearGradient

type LinearGradient struct {
	// X1 is the x coordinate of the first point.
	X1 float32
	// Y1 is the y coordinate of the first point.
	Y1 float32
	// X2 is the x coordinate of the second point.
	X2 float32
	// Y2 is the y coordinate of the second point.
	Y2 float32
	// Transform is a transform that should be applied to the linear
	// gradient.
	Transform Transform
	// SpreadMethod is the spread method of the linear gradient.
	SpreadMethod SpreadMethod
	// Stops holds the color stops of the linear gradient.
	//
	// Note that all stops need to be in the same color space. A gradient
	// without stops paints nothing.
	Stops []Stop
	// AntiAlias is whether the gradient should be anti-aliased.
	AntiAlias bool
	// Extend says which ends extend past the stops, for the spread method
	// pad. It is not in krilla (D68). The zero value extends both ends, as
	// krilla does.
	Extend ExtendMode
}

LinearGradient is LinearGradient in krilla src/graphics/paint.rs. The zero Transform of Go is not the identity, so a caller sets Transform, such as to path.IdentityTransform(), the Default of upstream.

A linear gradient.

type LinkAction added in v0.16.0

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

LinkAction is LinkAction in krilla src/interactive/action.rs.

A link action. Will open a link when clicked.

func NewLinkAction added in v0.16.0

func NewLinkAction(uri string) LinkAction

NewLinkAction is LinkAction::new in krilla src/interactive/action.rs.

Create a new link action that will open a URI when clicked.

type LinkAnnotation added in v0.16.0

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

LinkAnnotation is LinkAnnotation in krilla src/interactive/annotation.rs. krilla panics in NewLinkAnnotationWithQuadPoints for quadrilaterals that give no rectangle. The port keeps the error in the field err, and Document.Finish returns it.

A link annotation.

func NewLinkAnnotation added in v0.16.0

func NewLinkAnnotation(rect Rect, target Target) LinkAnnotation

NewLinkAnnotation is LinkAnnotation::new in krilla src/interactive/annotation.rs. A nil target makes Document.Finish return ErrPDFInvalidAnnotation.

Create a new link annotation.

rect: The bounding box of the link annotation that it should cover on the page. target: The target of the link annotation.

func NewLinkAnnotationWithQuadPoints added in v0.16.0

func NewLinkAnnotationWithQuadPoints(quadPoints []Quadrilateral, target Target) LinkAnnotation

NewLinkAnnotationWithQuadPoints is LinkAnnotation::new_with_quad_points in krilla src/interactive/annotation.rs. krilla panics when the list is empty, or when the bounding box of the points is not a valid rectangle, such as for a point that is not finite. Document.Finish returns ErrPDFInvalidAnnotation in its place.

Create a new link annotation.

target: The target of the link annotation. quadPoints: An array of quadrilaterals that define where the link annotation should be activated. This is useful if you for example have a link annotation that is broken to one or multiple lines.

func (LinkAnnotation) WithBorder added in v0.16.0

func (l LinkAnnotation) WithBorder(border LinkBorder) LinkAnnotation

WithBorder is LinkAnnotation::with_border in krilla src/interactive/annotation.rs.

Set a border for this link annotation. The border will be visible on screen but not when printed, unless when exporting with PDF/A standard.

type LinkBorder added in v0.16.0

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

LinkBorder is LinkBorder in krilla src/interactive/annotation.rs.

Border of a link annotation.

func NewLinkBorder added in v0.16.0

func NewLinkBorder(width float32, color Color) LinkBorder

NewLinkBorder is LinkBorder::new in krilla src/interactive/annotation.rs.

Create a new link annotation border.

width: The width of the border in pt. color: The color of the border.

type Location

type Location uint64

Location is Location in krilla src/surface.rs, a NonZeroU64. The port declares it here, because Document.SetLocation takes it. Zero is no location, as the None of an Option<Location> of upstream.

A location that a program gives to the drawing operations that follow, so that an error of the export names where it comes from.

type MIMEType added in v0.22.0

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

MIMEType is MimeType in krilla src/interchange/embed.rs.

A mime type.

func NewMIMEType added in v0.22.0

func NewMIMEType(mimeType string) (*MIMEType, bool)

NewMIMEType is MimeType::new in krilla src/interchange/embed.rs. It returns false where upstream returns None.

Create a new mime type.

Returns false if the mime type is invalid.

func (*MIMEType) String added in v0.22.0

func (m *MIMEType) String() string

String returns the mime type.

type Mask

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

Mask is Mask in krilla src/graphics/mask.rs. Surface.PushMask takes it.

A mask. Can be a luminance mask or an alpha mask.

IMPORTANT: Note that you must only use a mask in the document that you created it with! If you use it in a different document, you will end up with an invalid PDF file.

func NewMask

func NewMask(stream *Stream, maskType MaskType) *Mask

NewMask is Mask::new in krilla src/graphics/mask.rs.

Create a new mask. stream contains the content description of the mask, and maskType indicates the type of mask.

func (*Mask) WithBackdrop added in v0.17.0

func (m *Mask) WithBackdrop(c ColorRGB) *Mask

WithBackdrop returns a copy of the mask with the backdrop color BC. A viewer composites the content of a luminosity mask over an opaque backdrop of this color, as okage.MaskFromLuminance does (D56). The group of the mask is in the RGB color space, so the color is an RGB color. A mask of the type alpha ignores the backdrop. It is not in krilla (D68).

func (*Mask) WithTransfer added in v0.17.0

func (m *Mask) WithTransfer(table *[256]uint8) *Mask

WithTransfer returns a copy of the mask with the transfer function TR. A viewer changes each value v of the mask, from 0 to 255, to table[v], as okage.Mask.ApplyTransfer does (D56). The file holds the table as a sampled function of 256 samples of 8 bits. A nil table removes the transfer function. It is not in krilla (D68).

type MaskType

type MaskType uint8

MaskType is MaskType in krilla src/graphics/mask.rs.

A mask type.

const (
	// MaskTypeLuminosity is a luminosity mask.
	MaskTypeLuminosity MaskType = iota
	// MaskTypeAlpha is an alpha mask.
	MaskTypeAlpha
)

The values of MaskType.

type MeshGradient added in v0.17.0

type MeshGradient struct {
	// Triangles are the triangles of the mesh.
	Triangles []MeshTriangle
	// Transform maps the space of the triangles to the space of the user.
	// The zero Transform of Go is not the identity, so set it.
	Transform Transform
	// AntiAlias is whether the viewer anti-aliases the shading.
	AntiAlias bool
}

MeshGradient is a paint that fills a mesh of triangles with a color at each corner, which the viewer interpolates. It is the shading of type 4 of PDF, the free-form Gouraud-shaded triangle mesh, and the MeshGradient of okage (D55). A later triangle paints over an earlier one. Outside the triangles, the paint paints nothing. It is not in krilla (D68).

When a vertex has an opacity below 1, a soft mask holds the opacities, as a second shading of type 4 in the gray color space, as krilla does for the opacities of the stops of a gradient.

type MeshTriangle added in v0.17.0

type MeshTriangle [3]MeshVertex

MeshTriangle is a triangle of a MeshGradient.

type MeshVertex added in v0.17.0

type MeshVertex struct {
	// Point is the point of the corner.
	Point Point
	// Color is the color at the corner. Each vertex of a mesh must have a
	// color of the same color space.
	Color Color
	// Opacity is the opacity at the corner.
	Opacity NormalizedF32
}

MeshVertex is a corner of a triangle of a MeshGradient. It is not in krilla (D68).

type Metadata added in v0.16.0

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

Metadata is Metadata in krilla src/interchange/metadata/mod.rs. Each field of upstream that is an Option is a pointer here, and nil is None. A method that sets a field returns a copy of the metadata, as the builder of upstream does. The copy shares no slice and no map with the metadata it came from, so a slice that a method extends is copied first.

Metadata for a PDF document.

func NewMetadata added in v0.16.0

func NewMetadata() Metadata

NewMetadata is Metadata::new in krilla src/interchange/metadata/mod.rs.

Create new metadata.

func (Metadata) Authors added in v0.16.0

func (m Metadata) Authors(authors []string) Metadata

Authors is Metadata::authors in krilla src/interchange/metadata/mod.rs. An empty list leaves the authors as they are.

The authors of the document.

func (Metadata) CreationDate added in v0.16.0

func (m Metadata) CreationDate(creationDate DateTime) Metadata

CreationDate is Metadata::creation_date in krilla src/interchange/metadata/mod.rs.

The creation date of the document.

func (Metadata) Creator added in v0.16.0

func (m Metadata) Creator(creator string) Metadata

Creator is Metadata::creator in krilla src/interchange/metadata/mod.rs. An empty creator leaves the creator as it is.

The creator tool of the document.

func (Metadata) CustomField added in v0.16.0

func (m Metadata) CustomField(name, value string) (Metadata, bool)

CustomField is Metadata::custom_field in krilla src/interchange/metadata/mod.rs. It returns false where upstream returns None, with the metadata as it was.

Add a custom field to the document information dictionary.

If a field with the same name was already added, its value will be replaced. Returns false for empty names and names reserved for standard document information fields.

Note: Custom fields are ignored when exporting to PDF/A-2, PDF/A-3 and PDF/A-4. PDF/A-2 and PDF/A-3 readers ignore the document information dictionary, and in PDF/A-4 it may only contain ModDate.

func (Metadata) CustomXMPProperty added in v0.22.0

func (m Metadata) CustomXMPProperty(property Property) Metadata

CustomXMPProperty is Metadata::custom_xmp_property in krilla src/interchange/metadata/mod.rs.

Add a custom XMP property.

func (Metadata) CustomXMPSchema added in v0.22.0

func (m Metadata) CustomXMPSchema(schema Schema) Metadata

CustomXMPSchema is Metadata::custom_xmp_schema in krilla src/interchange/metadata/mod.rs.

Add a schema describing the properties of a custom XMP namespace.

func (Metadata) Description added in v0.16.0

func (m Metadata) Description(description string) Metadata

Description is Metadata::description in krilla src/interchange/metadata/mod.rs. An empty description leaves the description as it is.

The description of the document.

This should be a short, human-readable abstract, summary, or description of the topic of the document.

func (Metadata) DisplayDocTitle added in v0.16.0

func (m Metadata) DisplayDocTitle(displayDocTitle bool) Metadata

DisplayDocTitle is Metadata::display_doc_title in krilla src/interchange/metadata/mod.rs.

Whether the viewer should show the title of the document in its title bar, rather than the file name.

Validators that require it set it regardless.

func (Metadata) DocumentID added in v0.16.0

func (m Metadata) DocumentID(documentID string) Metadata

DocumentID is Metadata::document_id in krilla src/interchange/metadata/mod.rs.

A document ID.

This attribute will be used as an identifier for identifying different versions of the same document.

func (Metadata) Keywords added in v0.16.0

func (m Metadata) Keywords(keywords []string) Metadata

Keywords is Metadata::keywords in krilla src/interchange/metadata/mod.rs. An empty list leaves the keywords as they are.

The keywords that describe the document.

func (Metadata) Language added in v0.16.0

func (m Metadata) Language(language string) Metadata

Language is Metadata::language in krilla src/interchange/metadata/mod.rs. An empty language leaves the language as it is.

The main language of the document, as an RFC 3066 language tag.

This property is required for some export modes, like for example PDF/A-3a.

func (Metadata) PageLayout added in v0.16.0

func (m Metadata) PageLayout(pageLayout PageLayout) Metadata

PageLayout is Metadata::page_layout in krilla src/interchange/metadata/mod.rs.

How the viewer should lay out the pages.

func (Metadata) Producer added in v0.16.0

func (m Metadata) Producer(producer string) Metadata

Producer is Metadata::producer in krilla src/interchange/metadata/mod.rs. An empty producer leaves the producer as it is.

The producer tool of the document.

func (Metadata) TextDirection added in v0.16.0

func (m Metadata) TextDirection(textDirection TextDirectionMetadata) Metadata

TextDirection is Metadata::text_direction in krilla src/interchange/metadata/mod.rs.

The main text direction of the document.

func (Metadata) Title added in v0.16.0

func (m Metadata) Title(title string) Metadata

Title is Metadata::title in krilla src/interchange/metadata/mod.rs. An empty title leaves the title as it is.

The title of the document.

func (Metadata) Trapped added in v0.19.0

func (m Metadata) Trapped(trapped bool) Metadata

Trapped is Metadata::trapped in krilla src/interchange/metadata/mod.rs.

Whether the document has been trapped.

If this is not set, the trapping status is unknown.

func (Metadata) VersionID added in v0.16.0

func (m Metadata) VersionID(versionID string) Metadata

VersionID is Metadata::version_id in krilla src/interchange/metadata/mod.rs. It goes only into the XMP metadata.

A version ID.

This attribute identifies a specific version of the document.

type NamedDestination added in v0.16.0

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

NamedDestination is NamedDestination in krilla src/interactive/destination.rs.

A destination associated with a name.

func NewNamedDestination added in v0.16.0

func NewNamedDestination(name string, xyzDest XYZDestination) NamedDestination

NewNamedDestination is NamedDestination::new in krilla src/interactive/destination.rs.

Create a new named destination.

When used as part of a link annotation, the destination will be automatically registered with the Document.

That said, you can also manually register a destination without linking to it by calling Document.RegisterNamedDestination.

type Namespace added in v0.22.0

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

Namespace is Namespace in krilla src/interchange/metadata/xmp.rs.

An XMP namespace, identified by its URI.

The prefix is the short name used in the serialized XML.

func NewNamespace added in v0.22.0

func NewNamespace(prefix, uri string) Namespace

NewNamespace is Namespace::new in krilla src/interchange/metadata/xmp.rs.

Create a new namespace with the given prefix (e.g. "fx") and URI (e.g. "urn:factur-x:pdfa:CrossIndustryDocument:invoice:1p0#").

func (Namespace) Prefix added in v0.22.0

func (n Namespace) Prefix() string

Prefix is Namespace::prefix in krilla src/interchange/metadata/xmp.rs.

The prefix of the namespace.

func (Namespace) Property added in v0.22.0

func (n Namespace) Property(name string, value Value) Property

Property is Namespace::property in krilla src/interchange/metadata/xmp.rs.

Create a property in this namespace.

func (Namespace) URI added in v0.22.0

func (n Namespace) URI() string

URI is Namespace::uri in krilla src/interchange/metadata/xmp.rs.

The URI of the namespace.

type NormalizedF32

type NormalizedF32 = path.NormalizedF32

NormalizedF32 is NormalizedF32 in krilla src/num.rs. krilla wraps the NormalizedF32 of tiny-skia-path, and the port takes the one of path.

An immutable, finite float32 in a 0..=1 range.

func NewNormalizedF32

func NewNormalizedF32(num float32) (NormalizedF32, bool)

NewNormalizedF32 is NormalizedF32::new in krilla src/num.rs. It returns false if the number is not finite or not in the range 0..=1.

Create a new normalized f32.

type NumberingStyle

type NumberingStyle uint8

NumberingStyle is NumberingStyle in krilla src/page.rs.

The numbering style of a page label.

const (
	// NumberingStyleArabic is NumberingStyle::Arabic. Arabic numerals.
	NumberingStyleArabic NumberingStyle = iota
	// NumberingStyleLowerRoman is NumberingStyle::LowerRoman. Lowercase
	// Roman numerals.
	NumberingStyleLowerRoman
	// NumberingStyleUpperRoman is NumberingStyle::UpperRoman. Uppercase
	// Roman numerals.
	NumberingStyleUpperRoman
	// NumberingStyleLowerAlpha is NumberingStyle::LowerAlpha. Lowercase
	// letters (a-z, then aa-zz, ...).
	NumberingStyleLowerAlpha
	// NumberingStyleUpperAlpha is NumberingStyle::UpperAlpha. Uppercase
	// letters (A-Z, then AA-ZZ, ...).
	NumberingStyleUpperAlpha
)

The values of NumberingStyle.

type Option

type Option func(*serializeSettings)

Option is an option of NewDocument. Each option sets one field of the struct SerializeSettings of krilla src/serialize.rs (D20).

func WithASCIICompatible

func WithASCIICompatible(asciiCompatible bool) Option

WithASCIICompatible is the field ascii_compatible of SerializeSettings in krilla src/serialize.rs. The default is false.

Whether the PDF should be ASCII-compatible, i.e. only consist of characters in the ASCII range. This is only on a best-effort basis.

func WithArchivalValidator added in v0.22.0

func WithArchivalValidator(archival Archival) Option

WithArchivalValidator is the validator of PDF/A of the field configuration of SerializeSettings in krilla src/serialize.rs, as ConfigurationBuilder::with_archival_validator sets it (D99). The default is no validator.

With a validator, the document is written in a way that conforms to the standard, for example with its metadata, and Document.Finish returns an error that wraps ErrPDFValidation for each input that the standard does not allow. Some requirements are semantic in nature and cannot be validated. The caller must make sure that they are fulfilled.

func WithCMYKProfile

func WithCMYKProfile(profile *ICCProfile) Option

WithCMYKProfile is the field cmyk_profile of SerializeSettings in krilla src/serialize.rs. The default is nil, which is None. The type ICCProfile<4> of upstream takes only a profile with four components. The option takes nil in place of a profile with another number of components.

The ICC profile that should be used for CMYK colors when no_device_cs is enabled.

This is usually not required, but it is for example required when exporting to PDF/A and using a CMYK color, since they have to be device-independent.

func WithCompression

func WithCompression(compress bool) Option

WithCompression is the field compress_content_streams of SerializeSettings in krilla src/serialize.rs. The default is true.

Whether content streams should be compressed. Leads to significantly smaller file sizes, but also longer running times. It is highly recommended that you set this to true.

func WithLogger added in v0.19.0

func WithLogger(logger *slog.Logger) Option

WithLogger is not in krilla. The document logs to the logger, and without it, the document logs nothing (D20). The default is nil.

func WithNoDeviceCS

func WithNoDeviceCS(noDeviceCS bool) Option

WithNoDeviceCS is the field no_device_cs of SerializeSettings in krilla src/serialize.rs. The default is false.

Whether device-independent colors should be used instead of device-dependent ones.

func WithPDFVersion

func WithPDFVersion(version PDFVersion) Option

WithPDFVersion is the version of the field configuration of SerializeSettings in krilla src/serialize.rs, as ConfigurationBuilder::with_version sets it. NewDocument builds the configuration with ConfigurationBuilder::finish after the last option. The default is PDF17, or the highest version of the validator of WithArchivalValidator. A version that is not one of the constants of PDFVersion, or that the validator does not allow, makes Document.Finish return ErrPDFVersion.

func WithPretty

func WithPretty(pretty bool) Option

WithPretty is the field pretty of SerializeSettings in krilla src/serialize.rs. The default is false.

Whether to write PDFs in a way that is easier to inspect manually. This will result in larger file sizes.

func WithSVGGlyphs added in v0.16.0

func WithSVGGlyphs(fn SVGGlyphFunc) Option

WithSVGGlyphs is the field render_svg_glyph_fn of SerializeSettings in krilla src/serialize.rs. The default is nil, the default function of upstream, which draws no SVG glyph. The surface then draws the bitmap or the outline of such a glyph.

A function that should be used to render SVG glyphs. It is recommended that you use the function of the package pdfsvg.

func WithSubsetFallback added in v0.19.0

func WithSubsetFallback(fallback bool) Option

WithSubsetFallback is not in krilla. The default is true (D80).

When the subset of a font fails in Document.Finish and fallback is true, the document draws each glyph of that font as a path, in the place of the text, with the fill and the stroke of the text. The text stays in the file as invisible text, with the font without its font program, so that a reader can copy and search it. Finish then returns no error for the font, and logs the font and the error of the subset to the logger of WithLogger. When fallback is false, Finish returns the error, as krilla does.

func WithXMPMetadata added in v0.22.0

func WithXMPMetadata(xmpMetadata bool) Option

WithXMPMetadata is the field xmp_metadata of SerializeSettings in krilla src/serialize.rs. The default is true.

Whether the PDF should include XMP metadata.

Note that this value might be overridden depending on which validator you use. For example, when exporting to PDF/A, this value will be set to true, regardless of what value will be passed.

type Outline added in v0.16.0

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

Outline is Outline in krilla src/interchange/outline.rs. The zero value is an empty outline, as Outline::new and the Default of upstream.

An outline.

This represents the root of the outline tree.

func NewOutline added in v0.16.0

func NewOutline() Outline

NewOutline is Outline::new in krilla src/interchange/outline.rs.

Create a new, empty outline.

func (*Outline) PushChild added in v0.16.0

func (o *Outline) PushChild(node OutlineNode)

PushChild is Outline::push_child in krilla src/interchange/outline.rs.

Push a new child (which may in turn contain other children) to the outline.

type OutlineNode added in v0.16.0

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

OutlineNode is OutlineNode in krilla src/interchange/outline.rs.

An outline node.

This represents either an intermediate node in the outline tree, or a leaf node if it does not contain any further children itself.

func NewOutlineNode added in v0.16.0

func NewOutlineNode(text string, destination XYZDestination) OutlineNode

NewOutlineNode is OutlineNode::new in krilla src/interchange/outline.rs.

Create a new outline node.

text is the string that should be displayed in the outline tree, and destination is the destination that should be jumped to when clicking on the outline entry.

func (*OutlineNode) PushChild added in v0.16.0

func (n *OutlineNode) PushChild(node OutlineNode)

PushChild is OutlineNode::push_child in krilla src/interchange/outline.rs.

Add a new child to the outline node.

func (OutlineNode) WithOpen added in v0.16.0

func (n OutlineNode) WithOpen(open bool) OutlineNode

WithOpen is OutlineNode::with_open in krilla src/interchange/outline.rs.

Set whether this node is initially open (children shown expanded).

If open is true, the node's children will be shown expanded when the document is opened in a PDF viewer. If false, the children will be collapsed. Leaf nodes (nodes without children) are unaffected by this flag.

By default, this flag is set to false.

type PDFVersion

type PDFVersion uint8

PDFVersion is PdfVersion in krilla src/configure/version.rs. The versions are in their order, so that a comparison of two versions is the comparison of upstream.

The version of a PDF document.

const (
	// PDF14 is PdfVersion::Pdf14, PDF 1.4.
	PDF14 PDFVersion = iota
	// PDF15 is PdfVersion::Pdf15, PDF 1.5.
	PDF15
	// PDF16 is PdfVersion::Pdf16, PDF 1.6.
	PDF16
	// PDF17 is PdfVersion::Pdf17, PDF 1.7.
	PDF17
	// PDF20 is PdfVersion::Pdf20, PDF 2.0.
	PDF20
)

The values of PDFVersion. The default of a document is PDF17.

func (PDFVersion) String

func (v PDFVersion) String() string

String is PdfVersion::as_str in krilla src/configure/version.rs.

Get a string representation of the PDF version.

type Page

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

Page is Page in krilla src/page.rs. Document.StartPage makes one. The method Surface of upstream makes a Surface, and the port of surface.rs adds it, as the package comment says. The methods add_tagged_annotation and add_widget_annotation are for the tags and the forms, which the base port leaves out (D62).

A single page.

In most cases, all you need to do is to call the method Surface, so you can start drawing on the page. However, there are a few other operations you can perform, such as adding annotations to a page.

func (*Page) AddAnnotation added in v0.16.0

func (p *Page) AddAnnotation(annotation Annotation)

AddAnnotation is Page::add_annotation in krilla src/page.rs. An annotation that is added after Page.Finish is not written.

Add an annotation to the page.

func (*Page) Finish

func (p *Page) Finish()

Finish is the impl Drop for Page in krilla src/page.rs, which the method finish of upstream runs. It finishes the open surface of the page first. A second call does nothing. Document.StartPage and Document.Finish call it for a page that is not finished.

The struct parent of the page of upstream is for the tags, which the base port leaves out (D62).

func (*Page) Surface

func (p *Page) Surface() *Surface

Surface is Page::surface in krilla src/page.rs.

Get the surface of the page to draw on. Calling this multiple times on the same page will reset any previous drawings.

type PageLabel

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

PageLabel is PageLabel in krilla src/page.rs. Each field of upstream is an Option. A field of the port has a flag for Some, except the offset, which is a NonZeroU32 of upstream, so 0 is None.

A page label.

func NewPageLabel

func NewPageLabel(style *NumberingStyle, prefix *string, offset uint32) PageLabel

NewPageLabel is PageLabel::new in krilla src/page.rs. A nil style or prefix is None, and an offset of 0 is None.

Create a new page label.

type PageLayout added in v0.16.0

type PageLayout uint8

PageLayout is PageLayout in krilla src/interchange/metadata/mod.rs.

How the viewer should lay out the pages.

const (
	// PageLayoutSinglePage is PageLayout::SinglePage. Only a single page at
	// a time.
	PageLayoutSinglePage PageLayout = iota
	// PageLayoutOneColumn is PageLayout::OneColumn. A single, continuously
	// scrolling column of pages.
	PageLayoutOneColumn
	// PageLayoutTwoColumnLeft is PageLayout::TwoColumnLeft. Two continuously
	// scrolling columns of pages, laid out with odd-numbered pages on the
	// left.
	PageLayoutTwoColumnLeft
	// PageLayoutTwoColumnRight is PageLayout::TwoColumnRight. Two
	// continuously scrolling columns of pages, laid out with odd-numbered
	// pages on the right (like in a left-bound book).
	PageLayoutTwoColumnRight
	// PageLayoutTwoPageLeft is PageLayout::TwoPageLeft. Only two pages are
	// visible at a time, laid out with odd-numbered pages on the left. PDF
	// 1.5+.
	PageLayoutTwoPageLeft
	// PageLayoutTwoPageRight is PageLayout::TwoPageRight. Only two pages are
	// visible at a time, laid out with odd-numbered pages on the right (like
	// in a left-bound book). PDF 1.5+.
	PageLayoutTwoPageRight
)

The values of PageLayout.

type PageSettings

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

PageSettings is PageSettings in krilla src/page.rs. An optional box of upstream is a pointer, and nil is None.

The settings of a page.

func DefaultPageSettings

func DefaultPageSettings() PageSettings

DefaultPageSettings is the Default of PageSettings in krilla src/page.rs: the size of A4, 595 by 842.

func NewPageSettings

func NewPageSettings(mediaBox Rect) PageSettings

NewPageSettings is PageSettings::new in krilla src/page.rs.

Create new page settings with the given media box.

The media box defines the visible area of the page in the coordinate system of its surface. In the majority of cases, you want it to be aligned at the origin of the coordinate system, which is what PageSettingsFromWH does.

func PageSettingsFromWH

func PageSettingsFromWH(width, height float32) (PageSettings, bool)

PageSettingsFromWH is PageSettings::from_wh in krilla src/page.rs.

Try to create new page settings with the specified width and height and a media box that is aligned at the origin.

Returns false if either the width or the height is not > 0.

func (PageSettings) WithArtBox

func (s PageSettings) WithArtBox(artBox *Rect) PageSettings

WithArtBox is PageSettings::with_art_box in krilla src/page.rs.

Change the art box.

The art box defines the extent of the page's meaningful content (including potential white space) as intended by the page's creator.

If nil, no /ArtBox attribute will be written to the page.

func (PageSettings) WithBleedBox

func (s PageSettings) WithBleedBox(bleedBox *Rect) PageSettings

WithBleedBox is PageSettings::with_bleed_box in krilla src/page.rs.

Change the bleed box.

The bleed box defines the region to which the page contents needs to be clipped when output in a production environment. It includes any extra bleed area needed for printing.

If nil, no /BleedBox attribute will be written to the page.

func (PageSettings) WithCropBox

func (s PageSettings) WithCropBox(cropBox *Rect) PageSettings

WithCropBox is PageSettings::with_crop_box in krilla src/page.rs.

Change the crop box.

The crop box defines the region to which the page contents are to be clipped when displayed or printed. Default is the media box.

If nil, no /CropBox attribute will be written to the page.

func (PageSettings) WithPageLabel

func (s PageSettings) WithPageLabel(pageLabel PageLabel) PageSettings

WithPageLabel is PageSettings::with_page_label in krilla src/page.rs.

Change the page label.

func (PageSettings) WithTrimBox

func (s PageSettings) WithTrimBox(trimBox *Rect) PageSettings

WithTrimBox is PageSettings::with_trim_box in krilla src/page.rs.

Change the trim box.

The trim box defines the intended dimensions of the finished page after trimming. It can be smaller than the media box and bleed box to accommodate bleed for printing.

If nil, no /TrimBox attribute will be written to the page.

type Paint

type Paint interface {
	// contains filtered or unexported methods
}

Paint is Paint in krilla src/graphics/paint.rs, with the enum InnerPaint that it wraps. A Rust enum with data becomes an interface with one type for each case: ColorRGB, ColorLuma and ColorCMYK, which are each a Color, LinearGradient, RadialGradient, SweepGradient and Pattern. The impl From of upstream for each type is the conversion of the type into the interface. The Arc of the case Pattern is a copy of the value, which holds a pointer to its stream. A type switch on a Paint is the match on InnerPaint of upstream, with the case Color first.

A paint.

type Path

type Path = path.Path

Path is Path in krilla src/geom.rs.

A path.

type PathBuilder

type PathBuilder = path.PathBuilder

PathBuilder is PathBuilder in krilla src/geom.rs.

A path builder.

type Pattern

type Pattern struct {
	// Stream is the stream of the pattern.
	Stream *Stream
	// Transform is a transform that should be applied to the pattern.
	Transform Transform
	// Width is the width of the pattern.
	Width float32
	// Height is the height of the pattern.
	Height float32
}

Pattern is Pattern in krilla src/graphics/paint.rs. The zero Transform of Go is not the identity, so a caller sets Transform.

A pattern.

IMPORTANT: Note that you must only use a pattern in the document that you created it with! If you use it in a different document, you will end up with an invalid PDF file.

type Point

type Point = path.Point

Point is Point in krilla src/geom.rs.

A point.

type PredefinedStruct added in v0.22.0

type PredefinedStruct uint8

PredefinedStruct is PredefinedStruct in krilla src/interchange/metadata/xmp.rs.

A structure type defined by the XMP specification.

const (
	// PredefinedStructDimensions is the dimensions of a document (stDim).
	PredefinedStructDimensions PredefinedStruct = iota
	// PredefinedStructThumbnail is a thumbnail image (xmpGImg).
	PredefinedStructThumbnail
	// PredefinedStructResourceEvent is a high-level event in the history of
	// a resource (stEvt).
	PredefinedStructResourceEvent
	// PredefinedStructResourceRef is a reference to another resource
	// (stRef).
	PredefinedStructResourceRef
	// PredefinedStructVersion is a version of a document (stVer).
	PredefinedStructVersion
	// PredefinedStructJob is a job (stJob).
	PredefinedStructJob
	// PredefinedStructColorant is a colorant (xmpG).
	PredefinedStructColorant
	// PredefinedStructFont is a font (stFnt).
	PredefinedStructFont
)

The values of PredefinedStruct.

func (PredefinedStruct) String added in v0.22.0

func (t PredefinedStruct) String() string

String is PredefinedStruct::as_str in krilla src/interchange/metadata/xmp.rs. A value that is not one of the constants gives PredefinedStruct(n).

type Property added in v0.22.0

type Property struct {
	// Namespace is the namespace this property belongs to.
	Namespace Namespace
	// Name is the property name within the namespace.
	Name string
	// Value is the property value.
	Value Value
}

Property is Property in krilla src/interchange/metadata/xmp.rs.

A single XMP property in a Namespace.

Also used for the fields of a struct value, which are named values in a namespace just like top-level properties.

func NewProperty added in v0.22.0

func NewProperty(namespace Namespace, name string, value Value) Property

NewProperty is Property::new in krilla src/interchange/metadata/xmp.rs.

Create a new XMP property.

type PropertyDescription added in v0.22.0

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

PropertyDescription is PropertyDescription in krilla src/interchange/metadata/xmp.rs.

Description of a single XMP property, or of a field of a StructType.

func NewPropertyDescription added in v0.22.0

func NewPropertyDescription(name string, valueType IntoValueType, description string) PropertyDescription

NewPropertyDescription is PropertyDescription::new in krilla src/interchange/metadata/xmp.rs.

Create a new description of an optional, external property.

func (PropertyDescription) Internal added in v0.22.0

Internal is PropertyDescription::internal in krilla src/interchange/metadata/xmp.rs.

Mark the property as being generated internally by the producer.

func (PropertyDescription) Required added in v0.22.0

Required is PropertyDescription::required in krilla src/interchange/metadata/xmp.rs.

Mark the property as required.

type Quadrilateral

type Quadrilateral [4]Point

Quadrilateral is Quadrilateral in krilla src/geom.rs.

A quadrilateral.

The points should be given in the following order:

  1. bottom-left
  2. bottom-right
  3. top-right
  4. top-left

Where the coordinate system is Y-down.

func QuadrilateralFromRect

func QuadrilateralFromRect(r Rect) Quadrilateral

QuadrilateralFromRect is the impl From<Rect> for Quadrilateral in krilla src/geom.rs.

type RadialGradient

type RadialGradient struct {
	// Fx is the x coordinate of the start circle.
	Fx float32
	// Fy is the y coordinate of the start circle.
	Fy float32
	// Fr is the radius of the start circle.
	Fr float32
	// Cx is the x coordinate of the end circle.
	Cx float32
	// Cy is the y coordinate of the end circle.
	Cy float32
	// Cr is the radius of the end circle.
	Cr float32
	// Transform is a transform that should be applied to the radial
	// gradient.
	Transform Transform
	// SpreadMethod is the spread method of the radial gradient.
	//
	// Note: The spread methods Repeat and Reflect are currently not
	// supported for radial gradients, and will fall back to Pad.
	SpreadMethod SpreadMethod
	// Stops holds the color stops of the radial gradient.
	//
	// Note that all stops need to be in the same color space. A gradient
	// without stops paints nothing.
	Stops []Stop
	// AntiAlias is whether the gradient should be anti-aliased.
	AntiAlias bool
	// Extend says which circles extend past the stops. It is not in krilla
	// (D68). The zero value extends both circles, as krilla does.
	Extend ExtendMode
}

RadialGradient is RadialGradient in krilla src/graphics/paint.rs. The zero Transform of Go is not the identity, so a caller sets Transform.

A radial gradient.

type RasterOption added in v0.20.0

type RasterOption func(*rasterOptions)

RasterOption is an option of Surface.DrawRaster (D20).

func WithRasterArea added in v0.20.0

func WithRasterArea(area Rect) RasterOption

WithRasterArea gives DrawRaster the area of its rectangle on the page, from which it takes the resolution of the pixmap. Without it, the area is the rectangle under the current transform. pdfsvg gives the area that render of krilla-svg src/filter.rs computes: the bounding box of a group under the current transform, and then under the transform of the group.

type Rect

type Rect = path.Rect

Rect is Rect in krilla src/geom.rs. path.RectFromLTRB and path.RectFromXYWH make one.

A rectangle defined by left, top, right and bottom edges.

type SVGGlyphFunc added in v0.16.0

type SVGGlyphFunc func(data []byte, contextColor ColorRGB, glyph GlyphID, width, height float32, s *Surface) bool

SVGGlyphFunc is RenderSvgGlyphFn in krilla src/serialize.rs. It draws the SVG document of a glyph onto a surface, in the units of the font, and returns false where upstream returns None. data is the document of the glyph in the table SVG, which can be compressed with gzip. width and height are the units per em of the font. pdfsvg gives RenderGlyph, which draws the document with the package svg.

type Schema added in v0.22.0

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

Schema is Schema in krilla src/interchange/metadata/xmp.rs. A method returns a copy of the schema, as the builder of upstream does, and the copy shares no slice with the schema it came from.

A description of the properties in a Namespace.

func NewSchema added in v0.22.0

func NewSchema(namespace Namespace) Schema

NewSchema is Schema::new in krilla src/interchange/metadata/xmp.rs.

Create a new schema without any properties.

func (Schema) Description added in v0.22.0

func (s Schema) Description(description string) Schema

Description is Schema::description in krilla src/interchange/metadata/xmp.rs.

A human-readable description of the schema.

func (Schema) Name added in v0.22.0

func (s Schema) Name(name string) Schema

Name is Schema::name in krilla src/interchange/metadata/xmp.rs.

The human-readable name of the schema. Defaults to "<prefix> schema".

func (Schema) Property added in v0.22.0

func (s Schema) Property(property PropertyDescription) Schema

Property is Schema::property in krilla src/interchange/metadata/xmp.rs.

Describe a property of the schema.

type SimpleType added in v0.22.0

type SimpleType uint8

SimpleType is SimpleType in krilla src/interchange/metadata/xmp.rs.

A simple XMP value type.

Text, Boolean, Integer, Real and Date are the core simple types. The rest are derived from them and are all stored as text, but carry additional meaning.

const (
	// SimpleTypeText is unconstrained text.
	SimpleTypeText SimpleType = iota
	// SimpleTypeBoolean is a boolean, written as True or False.
	SimpleTypeBoolean
	// SimpleTypeInteger is an integer.
	SimpleTypeInteger
	// SimpleTypeReal is a floating-point number.
	SimpleTypeReal
	// SimpleTypeDate is a date and time.
	SimpleTypeDate
	// SimpleTypeAgentName is the name of an agent, i.e. a piece of
	// software.
	SimpleTypeAgentName
	// SimpleTypeGUID is a globally unique identifier.
	SimpleTypeGUID
	// SimpleTypeLocale is a language tag.
	SimpleTypeLocale
	// SimpleTypeMIMEType is a MIME type.
	SimpleTypeMIMEType
	// SimpleTypeProperName is the name of a person or organization.
	SimpleTypeProperName
	// SimpleTypeRenditionClass is the name of a rendition of a document.
	SimpleTypeRenditionClass
	// SimpleTypeURI is a URI.
	SimpleTypeURI
	// SimpleTypeURL is a URL.
	SimpleTypeURL
	// SimpleTypeRational is a rational number, written as
	// numerator/denominator.
	SimpleTypeRational
	// SimpleTypeFrameRate is a frame rate, written as f<frames> or
	// f<frames>s<basis>.
	SimpleTypeFrameRate
	// SimpleTypeFrameCount is a number of frames at a given frame rate.
	SimpleTypeFrameCount
	// SimpleTypePart is a path identifying a portion of a resource, e.g.
	// /content/audio.
	SimpleTypePart
	// SimpleTypeXPath is an XPath expression.
	SimpleTypeXPath
)

The values of SimpleType.

func (SimpleType) String added in v0.22.0

func (t SimpleType) String() string

String is SimpleType::as_str in krilla src/interchange/metadata/xmp.rs. A value that is not one of the constants gives SimpleType(n).

The name of the type in a PDF/A extension schema description.

type Size

type Size = path.Size

Size is Size in krilla src/geom.rs. path.SizeFromWH makes one.

A size.

type SpreadMethod

type SpreadMethod uint8

SpreadMethod is SpreadMethod in krilla src/graphics/paint.rs. The zero value is SpreadMethodPad, the Default of upstream.

A spread method.

const (
	// SpreadMethodPad is the pad spread method.
	SpreadMethodPad SpreadMethod = iota
	// SpreadMethodReflect is the reflect spread method.
	SpreadMethodReflect
	// SpreadMethodRepeat is the repeat spread method.
	SpreadMethodRepeat
)

The values of SpreadMethod.

type Stop

type Stop struct {
	// Offset is the normalized offset of the stop.
	Offset NormalizedF32
	// Color is the color of the stop.
	Color Color
	// Opacity is the opacity of the stop.
	Opacity NormalizedF32
}

Stop is Stop in krilla src/graphics/paint.rs.

A color stop in a gradient.

type Stream

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

Stream is Stream in krilla src/stream.rs. The field xobject_identifier of upstream is for the tags, which the base port leaves out (D62).

Drawing to a non-page context.

In most cases, all you need to do is to construct a document, add pages to it and draw on the surface of each page. A stream is a "sub-surface" that you draw on independently of the main page contents. There are two such situations: the contents of a mask, and the contents of a pattern. A StreamBuilder of the current surface gives the surface of a stream, and StreamBuilder.Finish returns the Stream, with which you then create a pattern or a mask.

type StreamBuilder

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

StreamBuilder is StreamBuilder in krilla src/stream.rs. The methods Surface and SurfaceWithBBox of upstream make a Surface, and the port of surface.rs adds them, as the package comment says.

A builder to create streams.

func (*StreamBuilder) Finish

func (b *StreamBuilder) Finish() *Stream

Finish is StreamBuilder::finish in krilla src/stream.rs.

Turn the stream builder into a stream.

func (*StreamBuilder) Surface

func (b *StreamBuilder) Surface() *Surface

Surface is StreamBuilder::surface in krilla src/stream.rs.

Get the surface of the stream builder.

func (*StreamBuilder) SurfaceWithBBox

func (b *StreamBuilder) SurfaceWithBBox(bbox Rect) *Surface

SurfaceWithBBox is StreamBuilder::surface_with_bbox in krilla src/stream.rs.

Get the surface of the stream builder. Unlike Surface, the returned surface has its y-axis inverted similarly to the surface of a page.

type Stroke

type Stroke struct {
	// Paint is the paint of the stroke.
	Paint Paint
	// Width is the width of the stroke.
	Width float32
	// MiterLimit is the miter limit of the stroke.
	MiterLimit float32
	// LineCap is the line cap of the stroke.
	LineCap LineCap
	// LineJoin is the line join of the stroke.
	LineJoin LineJoin
	// Opacity is the opacity of the stroke.
	Opacity NormalizedF32
	// Dash is the optional dash of the stroke. Nil is None.
	Dash *StrokeDash
}

Stroke is Stroke in krilla src/graphics/paint.rs. DefaultStroke gives the Default of upstream.

A stroke.

func DefaultStroke

func DefaultStroke() Stroke

DefaultStroke is the impl Default for Stroke in krilla src/graphics/paint.rs: a black stroke of width 1.

type StrokeDash

type StrokeDash struct {
	// Array is the dash array.
	Array []float32
	// Offset is the offset of the dash.
	Offset float32
}

StrokeDash is StrokeDash in krilla src/graphics/paint.rs.

A stroke dash.

type StructType added in v0.22.0

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

StructType is StructType in krilla src/interchange/metadata/xmp.rs. Upstream shares a structure type with an Arc. The port copies it into the value type that uses it. A method returns a copy of the type that shares no slice with the type it came from.

A user-defined structure type.

The fields of a structure are properties in the namespace of the type.

func NewStructType added in v0.22.0

func NewStructType(namespace Namespace, name, description string) StructType

NewStructType is StructType::new in krilla src/interchange/metadata/xmp.rs.

Create a new structure type without any fields.

func (StructType) Field added in v0.22.0

func (t StructType) Field(field PropertyDescription) StructType

Field is StructType::field in krilla src/interchange/metadata/xmp.rs.

Describe a field of the structure.

type Surface

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

Surface is Surface in krilla src/surface.rs.

A surface represents a drawing area for defining graphical content. The origin of the coordinate axis is in the top-left corner.

You cannot directly create an instance of a Surface yourself. Instead, there are two ways of getting access to a surface, which you can then use to draw on:

  • The first way, and also the most common one you will use, is by creating a new document, adding a page to it and then invoking the method Page.Surface. The surface returned as part of that represents the drawing area of the page.
  • The second way is by calling the method Surface.StreamBuilder, to create a sub-drawing context. See the documentation of Stream for more information.

The surface uses a push and pop based mechanism for applying certain actions. For example, the method PushTransform concatenates a new transform to the current transform matrix. The method PushClipPath intersects the current drawing area with a clip path. Once you call such a push method, the action that it invokes will be in place until you call the method Pop, which will then revert the last push operation. This allows you to, for example, define a clipping path area or a mask to use only for certain objects.

For each push method you invoke, there must be a corresponding call of Pop that reverts it. krilla panics when the pushes and the pops differ. The port records ErrPDFPushPop, which Document.Finish returns.

Rust drops a surface at the end of its scope. In Go, call Finish when the drawing is done. Page.Finish finishes the surface of the page. Finish the surface of a StreamBuilder before StreamBuilder.Finish. Do not use a surface after Finish.

func (*Surface) CTM

func (s *Surface) CTM() Transform

CTM is Surface::ctm in krilla src/surface.rs.

Return the current transformation matrix, relative to the outermost surface, usually the page.

This also accounts for the transforms that the current content stream will be drawn with, for example inside of PushMask, PushOpacity or PushIsolated. It is useful for determining at which resolution content should be rasterized.

Inside of a surface created with Surface.StreamBuilder, it is assumed that the stream will be drawn with the transformation matrix the builder was created at, which is not accurate if the stream is drawn somewhere else, for example as a pattern.

func (*Surface) DrawGlyphs added in v0.16.0

func (s *Surface) DrawGlyphs(start Point, glyphs []Glyph, font *Font, text string, fontSize float32, outlined bool)

DrawGlyphs is Surface::draw_glyphs in krilla src/surface.rs. text holds the characters of the clusters of the glyphs, which the TextRange of each glyph gives. A font draws the text that a reader can copy or search, from the text of each cluster (D62, question 27). When outlined is true, the glyphs are drawn as paths.

krilla panics for a glyph whose range is outside the text or does not fall on the bounds of its characters, and for a glyph ID above 65535 in a CID font. Unless outlined is true, the port then records the error of CheckGlyphs, which Document.Finish returns, and draws nothing.

Draw a sequence of glyphs using the currently active fill and/or stroke.

This is a very low-level method, which gives you full control over how to place the glyphs that make up the text. This means that you must have your own text processing logic for dealing with bidirectional text, font fallback, text layouting, etc.

func (*Surface) DrawGraphic

func (s *Surface) DrawGraphic(graphic Graphic)

DrawGraphic is Surface::draw_graphic in krilla src/surface.rs.

Draw a new graphic.

Drawing the same graphic multiple times is very cheap in terms of file size.

func (*Surface) DrawImage added in v0.16.0

func (s *Surface) DrawImage(img *Image, size Size)

DrawImage is Surface::draw_image in krilla src/surface.rs. It draws the image into the rectangle from 0, 0 to the size. krilla cannot take a missing image. The port records ErrPDFImage for a nil image, which Document.Finish returns, and draws nothing.

Draw a new bitmap image.

func (*Surface) DrawInvisibleGlyphs added in v0.24.0

func (s *Surface) DrawInvisibleGlyphs(start Point, glyphs []Glyph, font *Font, text string, fontSize float32)

DrawInvisibleGlyphs draws the glyphs with their text as invisible text, with the text rendering mode 3 (D106). The arguments are those of DrawGlyphs. The run embeds the font and adds its text to the ToUnicode map, as a visible run does, so that a reader can search, select and copy the text. The fill and the stroke of the surface do not apply, and the run adds no graphics state of its own.

As DrawGlyphs does, DrawInvisibleGlyphs records the error of CheckGlyphs for a glyph that it cannot draw, which Document.Finish returns, and then draws nothing.

func (*Surface) DrawPath

func (s *Surface) DrawPath(p *Path)

DrawPath is Surface::draw_path in krilla src/surface.rs.

Draw a path using the currently active fill and/or stroke.

func (*Surface) DrawRaster added in v0.17.0

func (s *Surface) DrawRaster(rect Rect, scale float32, draw func(pm *okage.Pixmap, t Transform), opts ...RasterOption) bool

DrawRaster draws a part of the surface with okage, and draws the pixmap as an image in its place. It is the fallback of D62 item 10, for a part that PDF cannot hold, such as a blend mode that PDF does not have. It is render in krilla-svg src/filter.rs, which draws a filter of SVG in this way, and pdfsvg draws its filters with it. It is not in krilla (D68).

rect is the area to draw, in the user space of the surface. The pixmap has the resolution of rect on the page, as the current transform gives it, in pixels for each unit of the page, times scale. WithRasterArea gives the area on the page in place of the current transform. A side of the pixmap has at most 5000 pixels. draw gets a transparent pixmap and the transform from the user space of the surface to the pixels of the pixmap. It draws onto the pixmap, and the surface then draws the pixmap as an image into rect.

The scale and the limit of 5000 pixels compare as f32::min and f32::max of Rust, which take the other value for a NaN, so a scale that is NaN gives the largest pixmap, as in krilla-svg. DrawRaster returns false and draws nothing when rect or scale give no pixel.

func (*Surface) DrawText added in v0.16.0

func (s *Surface) DrawText(start Point, font *Font, fontSize float32, text string, outlined bool, direction TextDirection)

DrawText is Surface::draw_text in krilla src/surface.rs. typesetting shapes the text (D52, D62).

Draw some text using the currently active fill and/or stroke.

This is a high-level method which allows you to just provide some text, which will then be rendered into a single line. However, this approach has restrictions:

  • It will not perform BIDI resolution and only supports a single script, meaning that you must ensure that your text does not contain multiple scripts.
  • It will only use the single font you provided to draw the text, no font fallback will be performed.

If you need more advanced control over how your text looks, you can use the method DrawGlyphs.

func (*Surface) FillStencil added in v0.17.0

func (s *Surface) FillStencil(mask *image.Alpha, size Size, interpolate bool)

FillStencil fills the rectangle from 0, 0 to size with the fill of the surface, through a stencil mask of 8 bits. The pixels of mask cover the rectangle as the pixels of an image of DrawImage do, and the alpha of each pixel is its coverage. This is the fill of a glyph bitmap or of a stencil mask of okage. With interpolate, a viewer can smooth the mask when it scales it. It is not in krilla (D68).

When the fill is a color and each pixel of the mask is 0 or 255, the file holds the mask as an image mask of 1 bit for each pixel, which the viewer fills with the color (D69). Otherwise, the file holds the mask as a gray image in a soft mask of the type luminosity. Without a fill, the surface fills with black, as DrawPath does. The stroke of the surface does not apply. A nil mask records ErrPDFImage, which Document.Finish returns. A mask with no pixel draws nothing.

func (*Surface) Finish

func (s *Surface) Finish()

Finish is Surface::finish and the impl Drop for Surface in krilla src/surface.rs. It gives the stream of the surface to its page or its StreamBuilder. A second call does nothing.

krilla panics when a push has no pop. The port then records ErrPDFPushPop, which Document.Finish returns, and pops the pushes that are left, so that the content stream stays valid.

func (*Surface) GetFill

func (s *Surface) GetFill() *Fill

GetFill is Surface::get_fill in krilla src/surface.rs. It returns a copy of the fill, or nil.

Get the currently active fill.

func (*Surface) GetStroke

func (s *Surface) GetStroke() *Stroke

GetStroke is Surface::get_stroke in krilla src/surface.rs. It returns a copy of the stroke, or nil.

Get the currently active stroke.

func (*Surface) PaintFromShader added in v0.17.0

func (s *Surface) PaintFromShader(shader okage.Shader) (Paint, NormalizedF32, bool)

PaintFromShader converts a shader of okage into a paint and an opacity. The caller sets them as the Paint and the Opacity of a Fill or a Stroke. It returns false for a shader that a paint cannot hold. The caller then draws that part with DrawRaster. It is not in krilla (D68).

The shaders convert in this way:

  • A SolidColor is a ColorRGB, and its alpha is the opacity.
  • A LinearGradient is a LinearGradient with the same spread mode. The decal spread mode is SpreadMethodPad with ExtendNone.
  • A RadialGradient with the spread mode pad or decal, or of NewRadialGradientExtend, is a RadialGradient with the ExtendMode of its flags. With the spread mode repeat or reflect, it does not convert, because krilla draws such a gradient with the mode pad.
  • A SweepGradient with the spread mode pad, repeat or reflect is a SweepGradient. With the decal spread mode, it does not convert.
  • A MeshGradient is a MeshGradient.
  • A Pattern with the spread mode repeat is a Pattern whose tile is its pixmap, and with the spread mode reflect a Pattern whose tile holds four mirrored copies of its pixmap. Its opacity is the opacity. A Pattern with the spread mode pad or decal does not convert.

A gradient keeps the alpha of each stop as the opacity of the stop. The colors are RGB colors of 8 bits. The conversion takes the colors as they are, which is the color space okage.ColorSpaceLinear of a Paint of okage, the default.

func (*Surface) Pop

func (s *Surface) Pop()

Pop is Surface::pop in krilla src/surface.rs. krilla panics when no push is left. The port then records ErrPDFPushPop, which Document.Finish returns, and does nothing.

Pop the last push instruction.

func (*Surface) PushBlendMode

func (s *Surface) PushBlendMode(blendMode BlendMode)

PushBlendMode is Surface::push_blend_mode in krilla src/surface.rs.

Push a new blend mode.

func (*Surface) PushClipPath

func (s *Surface) PushClipPath(p *Path, clipRule FillRule)

PushClipPath is Surface::push_clip_path in krilla src/surface.rs.

Push a new clip path.

func (*Surface) PushGroup added in v0.17.0

func (s *Surface) PushGroup(g Group)

PushGroup starts a transparency group. The content that the surface draws until the matching Pop goes into one form XObject with a group of the transparency type, which has the flags I and K of the group. Pop draws the XObject with a graphics state that holds the opacity, the blend mode and the soft mask of the group. It is not in krilla (D68).

krilla draws an opacity, a mask and an isolated group each as an XObject of its own. One group of PushGroup holds all of them, so that a group that is not isolated, or that is a knockout group, keeps its meaning in PDF.

func (*Surface) PushIsolated

func (s *Surface) PushIsolated()

PushIsolated is Surface::push_isolated in krilla src/surface.rs.

Push a new isolated layer.

func (*Surface) PushMask

func (s *Surface) PushMask(mask *Mask)

PushMask is Surface::push_mask in krilla src/surface.rs.

Push a new mask.

func (*Surface) PushOpacity

func (s *Surface) PushOpacity(opacity NormalizedF32)

PushOpacity is Surface::push_opacity in krilla src/surface.rs.

Push a new opacity, meaning that each subsequent graphics object will be rendered with a base opacity.

This stacks, meaning that if you do PushOpacity(0.5) twice, the resulting base opacity will be 0.25.

func (*Surface) PushStrokeAdjustment added in v0.17.0

func (s *Surface) PushStrokeAdjustment(adjust bool)

PushStrokeAdjustment sets the automatic stroke adjustment of PDF, the entry SA of the graphics state, for the strokes until the matching Pop. A viewer then draws a thin line with a width of at least one pixel, and puts its edges on the borders of the pixels, as Paint.StrokeAdjust of okage does (D54). It is not in krilla (D68).

func (*Surface) PushTransform

func (s *Surface) PushTransform(transform Transform)

PushTransform is Surface::push_transform in krilla src/surface.rs.

Concatenate a new transform to the current transformation matrix.

func (*Surface) ResetLocation

func (s *Surface) ResetLocation()

ResetLocation is Surface::reset_location in krilla src/surface.rs.

Reset the location that should be assumed for subsequent operations.

func (*Surface) SetFill

func (s *Surface) SetFill(fill *Fill)

SetFill is Surface::set_fill in krilla src/surface.rs. The surface keeps a copy of the fill, and nil is None.

Set the fill that should be used for the next drawing operation.

You can set it to nil if you want to disable filling (though if there is no active stroke, then krilla will choose to fill with black by default).

func (*Surface) SetLocation

func (s *Surface) SetLocation(location Location)

SetLocation is Surface::set_location in krilla src/surface.rs.

Set the location that should be assumed for subsequent operations.

func (*Surface) SetStroke

func (s *Surface) SetStroke(stroke *Stroke)

SetStroke is Surface::set_stroke in krilla src/surface.rs. The surface keeps a copy of the stroke, and nil is None.

Set the stroke that should be used for drawing operations.

You can set it to nil if you want to disable stroking.

func (*Surface) StreamBuilder

func (s *Surface) StreamBuilder() *StreamBuilder

StreamBuilder is Surface::stream_builder in krilla src/surface.rs.

Return a StreamBuilder to allow drawing on a sub-context.

type SweepGradient

type SweepGradient struct {
	// Cx is the x coordinate of the center.
	Cx float32
	// Cy is the y coordinate of the center.
	Cy float32
	// StartAngle is the start angle.
	StartAngle float32
	// EndAngle is the end angle.
	EndAngle float32
	// Transform is a transform that should be applied to the sweep
	// gradient.
	Transform Transform
	// SpreadMethod is the spread method of the sweep gradient.
	SpreadMethod SpreadMethod
	// Stops holds the color stops of the sweep gradient.
	//
	// Note that all stops need to be in the same color space. A gradient
	// without stops paints nothing.
	Stops []Stop
	// AntiAlias is whether the gradient should be anti-aliased.
	AntiAlias bool
}

SweepGradient is SweepGradient in krilla src/graphics/paint.rs. The zero Transform of Go is not the identity, so a caller sets Transform.

A sweep gradient.

Angles start from the right and go counter-clockwise with increasing values.

type Tag added in v0.16.0

type Tag [4]byte

Tag is Tag in krilla src/text/font.rs.

A 4-byte OpenType tag.

func TagFromString added in v0.16.0

func TagFromString(s string) (Tag, bool)

TagFromString is Tag::try_from_str in krilla src/text/font.rs. It returns false if the string is not 4 bytes in size.

Try to create a new tag from a string.

type Target added in v0.16.0

type Target interface {
	// contains filtered or unexported methods
}

Target is Target in krilla src/interactive/annotation.rs. The case Target::Destination is a Destination, and the case Target::Action is an Action. Each one satisfies Target.

An annotation target.

type TextDirection added in v0.16.0

type TextDirection uint8

TextDirection is TextDirection in krilla src/text/shape.rs.

The direction of a text.

const (
	// TextDirectionAuto determines the direction automatically.
	TextDirectionAuto TextDirection = iota
	// TextDirectionLeftToRight is left to right.
	TextDirectionLeftToRight
	// TextDirectionRightToLeft is right to left.
	TextDirectionRightToLeft
	// TextDirectionTopToBottom is top to bottom.
	TextDirectionTopToBottom
	// TextDirectionBottomToTop is bottom to top.
	TextDirectionBottomToTop
)

The values of TextDirection.

type TextDirectionMetadata added in v0.16.0

type TextDirectionMetadata uint8

TextDirectionMetadata is TextDirection in krilla src/interchange/metadata/mod.rs. The module text of krilla has a TextDirection of its own, for the direction of a run of text, so this one takes the name of its module as a suffix (D10).

The main text direction of the document.

const (
	// TextDirectionMetadataLeftToRight is TextDirection::LeftToRight.
	TextDirectionMetadataLeftToRight TextDirectionMetadata = iota
	// TextDirectionMetadataRightToLeft is TextDirection::RightToLeft.
	TextDirectionMetadataRightToLeft
)

The values of TextDirectionMetadata.

type TextRange added in v0.16.0

type TextRange struct {
	Start int
	End   int
}

TextRange is the Range<usize> of a cluster in krilla: the start and the end of its bytes in the text.

type Transform

type Transform = path.Transform

Transform is Transform in krilla src/geom.rs.

An affine transformation matrix.

Unlike other types, doesn't guarantee to be valid. This is Skia quirk. Meaning Transform(0, 0, 0, 0, 0, 0) is ok, while it's technically not. Non-finite values are also not an error.

type Value added in v0.22.0

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

Value is Value in krilla src/interchange/metadata/xmp.rs. A function gives each case, such as TextValue for Value::Text. The zero value is an empty text.

An XMP property value.

The cases mirror the value shapes supported by XMP/RDF: simple values, the three array kinds (rdf:Seq, rdf:Bag, rdf:Alt), language alternatives, and structs. URIs and URLs are written as URIValue, other derived types like agent names as TextValue.

func AlternativeArrayValue added in v0.22.0

func AlternativeArrayValue(items ...Value) Value

AlternativeArrayValue is Value::AlternativeArray in krilla src/interchange/metadata/xmp.rs.

An alternative array (rdf:Alt).

func BoolValue added in v0.22.0

func BoolValue(value bool) Value

BoolValue is Value::Bool in krilla src/interchange/metadata/xmp.rs.

A boolean value.

func DateValue added in v0.22.0

func DateValue(value DateTime) Value

DateValue is Value::Date in krilla src/interchange/metadata/xmp.rs.

A date value.

func IntegerValue added in v0.22.0

func IntegerValue(value int64) Value

IntegerValue is Value::Integer in krilla src/interchange/metadata/xmp.rs.

An integer value.

func LanguageAlternativeValue added in v0.22.0

func LanguageAlternativeValue(items ...LangText) Value

LanguageAlternativeValue is Value::LanguageAlternative in krilla src/interchange/metadata/xmp.rs.

A language-alternative array (rdf:Alt of xml:lang-tagged text).

Each entry pairs an optional RFC 3066 language tag (nil means x-default) with its text value.

func OrderedArrayValue added in v0.22.0

func OrderedArrayValue(items ...Value) Value

OrderedArrayValue is Value::OrderedArray in krilla src/interchange/metadata/xmp.rs.

An ordered array (rdf:Seq).

func RationalValue added in v0.22.0

func RationalValue(numerator int64, denominator uint64) Value

RationalValue is Value::Rational in krilla src/interchange/metadata/xmp.rs.

A rational number, given as numerator and denominator. The denominator must not be zero.

func RealValue added in v0.22.0

func RealValue(value float64) Value

RealValue is Value::Real in krilla src/interchange/metadata/xmp.rs.

A floating-point value. Must be finite.

func StructValue added in v0.22.0

func StructValue(fields ...Property) Value

StructValue is Value::Struct in krilla src/interchange/metadata/xmp.rs.

A struct value, given as its fields.

func TextValue added in v0.22.0

func TextValue(value string) Value

TextValue is Value::Text and Value::text in krilla src/interchange/metadata/xmp.rs.

A text value.

func URIValue added in v0.22.0

func URIValue(value string) Value

URIValue is Value::Uri and Value::uri in krilla src/interchange/metadata/xmp.rs.

A URI or URL, written as an rdf:resource attribute.

func UnorderedArrayValue added in v0.22.0

func UnorderedArrayValue(items ...Value) Value

UnorderedArrayValue is Value::UnorderedArray in krilla src/interchange/metadata/xmp.rs.

An unordered array (rdf:Bag).

type ValueType added in v0.22.0

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

ValueType is ValueType in krilla src/interchange/metadata/xmp.rs. The zero value is a simple text. A function gives each case with data, and LanguageAlternativeType gives the language alternative.

The type of an XMP value.

This mirrors the XMP type system: simple types, choices, the three array kinds, language alternatives and structures.

func AlternativeArrayType added in v0.22.0

func AlternativeArrayType(item IntoValueType) ValueType

AlternativeArrayType is ValueType::alternative_array in krilla src/interchange/metadata/xmp.rs.

An alternative array (rdf:Alt) of the given type.

func ClosedChoiceType added in v0.22.0

func ClosedChoiceType(ty SimpleType, values ...string) ValueType

ClosedChoiceType is ValueType::closed_choice in krilla src/interchange/metadata/xmp.rs.

One of values.

func LanguageAlternativeType added in v0.22.0

func LanguageAlternativeType() ValueType

LanguageAlternativeType is ValueType::LanguageAlternative in krilla src/interchange/metadata/xmp.rs.

A language alternative: an rdf:Alt of xml:lang-tagged text.

func OpenChoiceType added in v0.22.0

func OpenChoiceType(ty SimpleType, values ...string) ValueType

OpenChoiceType is ValueType::open_choice in krilla src/interchange/metadata/xmp.rs.

A value of the given type, typically one of values.

func OrderedArrayType added in v0.22.0

func OrderedArrayType(item IntoValueType) ValueType

OrderedArrayType is ValueType::ordered_array in krilla src/interchange/metadata/xmp.rs.

An ordered array (rdf:Seq) of the given type.

func UnorderedArrayType added in v0.22.0

func UnorderedArrayType(item IntoValueType) ValueType

UnorderedArrayType is ValueType::unordered_array in krilla src/interchange/metadata/xmp.rs.

An unordered array (rdf:Bag) of the given type.

type VariationCoord added in v0.16.0

type VariationCoord struct {
	Tag   Tag
	Value float32
}

VariationCoord is an item (Tag, f32) of the variation coordinates of Font::new_variable in krilla src/text/font.rs: the tag of an axis and a value in the coordinates of the user, such as 700 for the axis wght.

type XMPError added in v0.22.0

type XMPError struct {
	Kind XMPErrorKind
	Name string
}

XMPError is XmpError in krilla src/interchange/metadata/xmp.rs, and KrillaError::Xmp of krilla src/error.rs, which wraps it. It wraps okage.ErrPDFXMP (D21, D99), and its text is the Display text of KrillaError::Xmp.

An invalid set of custom XMP properties or schemas.

func (*XMPError) Error added in v0.22.0

func (e *XMPError) Error() string

Error gives the Display text of KrillaError::Xmp in krilla src/error.rs, after the text of okage.ErrPDFXMP.

func (*XMPError) Unwrap added in v0.22.0

func (e *XMPError) Unwrap() error

Unwrap returns okage.ErrPDFXMP.

type XMPErrorKind added in v0.22.0

type XMPErrorKind uint8

XMPErrorKind is the case of the enum XmpError in krilla src/interchange/metadata/xmp.rs.

const (
	// XMPErrorConflictingNamespace means that one namespace URI was used
	// with two different prefixes. The name is the namespace URI.
	XMPErrorConflictingNamespace XMPErrorKind = iota
	// XMPErrorConflictingPrefix means that one prefix was bound to two
	// different namespace URIs. The name is the prefix.
	XMPErrorConflictingPrefix
	// XMPErrorReservedPrefix means that a custom namespace used a prefix
	// reserved by a predefined XMP schema (e.g. dc, xmp, pdf) or by XML
	// (xml, xmlns). The name is the prefix.
	XMPErrorReservedPrefix
	// XMPErrorInvalidName means that a prefix, or the name of a property,
	// structure field or structure type, isn't a valid XML name without a
	// colon (an NCName). The name is that name.
	XMPErrorInvalidName
	// XMPErrorDuplicateSchema means that more than one schema was attached
	// for the same namespace. The name is the namespace URI.
	XMPErrorDuplicateSchema
	// XMPErrorInvalidNumber means that a real value was NaN or infinite, or
	// a rational value had a zero denominator. The name is the name of the
	// containing property.
	XMPErrorInvalidNumber
	// XMPErrorInvalidValue means that a value didn't match the type its
	// schema declared for it. The name is the name of the containing
	// property.
	XMPErrorInvalidValue
	// XMPErrorMissingProperty means that a property or structure field that
	// its schema marked as required was missing. The name is the name of the
	// property or field.
	XMPErrorMissingProperty
	// XMPErrorManagedProperty means that a property that krilla writes
	// itself was set. Such properties must be set via Metadata, if at all.
	// The name is the qualified name of the property.
	XMPErrorManagedProperty
	// XMPErrorDuplicateProperty means that a property or structure field was
	// set more than once. The name is its qualified name.
	XMPErrorDuplicateProperty
)

The cases of XmpError.

type XYZDestination added in v0.16.0

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

XYZDestination is XyzDestination in krilla src/interactive/destination.rs. Upstream holds the page index and the point in an Arc. The port holds them as values.

A destination pointing to a specific location at a specific page.

func NewXYZDestination added in v0.16.0

func NewXYZDestination(pageIndex int, point Point) XYZDestination

NewXYZDestination is XyzDestination::new in krilla src/interactive/destination.rs. krilla panics at the export when the page index is out of range. Document.Finish returns ErrPDFInvalidDestination in its place.

Create a new XYZ destination. pageIndex should be the index (i.e. number) of the target page, and point indicates the specific location on that page that should be targeted.

Jump to

Keyboard shortcuts

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