Documentation
¶
Overview ¶
Package pdf provides a PDF viewer widget for Fyne, written in pure Go.
Document is a ready-to-use viewer with a thumbnail strip and zoom controls. Source gives goroutine-safe low-level access to an opened PDF (page count, bounds, rendering, metadata), and NewImageFromMemory renders a single page without any UI.
Page indices are 0-based throughout the package.
Index ¶
- Constants
- Variables
- func NewImageFromMemory(contents []byte, pageNumber int, documentCallbacks ...DocumentCallbackFn) (image.Image, error)
- type Annotation
- type AnnotationPopup
- type Attachment
- type Destination
- type Document
- func (d *Document) Annotations(page int) []Annotation
- func (d *Document) Attachments() []Attachment
- func (d *Document) AttachmentsShown() bool
- func (d *Document) CanGoBack() bool
- func (d *Document) CanGoForward() bool
- func (d *Document) CanRedo() bool
- func (d *Document) CanUndo() bool
- func (d *Document) ClearSearch()
- func (d *Document) ClearSelection()
- func (d *Document) Close() error
- func (d *Document) CommentsShown() bool
- func (d *Document) Contents() []byte
- func (d *Document) CopySelection() bool
- func (d *Document) CreateRenderer() fyne.WidgetRenderer
- func (d *Document) CurrentPage() int
- func (d *Document) CurrentSearchResult() int
- func (d *Document) DeleteAnnotation(a Annotation) bool
- func (d *Document) Encrypted() bool
- func (d *Document) GoBack() bool
- func (d *Document) GoForward() bool
- func (d *Document) GoTo(dest Destination)
- func (d *Document) GoToLabel(label string) bool
- func (d *Document) LoadFromMemory(contents []byte) error
- func (d *Document) Metadata() Metadata
- func (d *Document) Modified() bool
- func (d *Document) MoveAnnotation(a Annotation, dx, dy float64) bool
- func (d *Document) NextSearchResult()
- func (d *Document) Outline() []OutlineItem
- func (d *Document) OutlineShown() bool
- func (d *Document) PageCount() int
- func (d *Document) PageLabel(page int) string
- func (d *Document) PageSize(page int) (width, height float64)
- func (d *Document) Permissions() Permissions
- func (d *Document) PreviousSearchResult()
- func (d *Document) Redo()
- func (d *Document) Refresh()
- func (d *Document) Resize(size fyne.Size)
- func (d *Document) Save(w io.Writer) error
- func (d *Document) Search(query string, opt SearchOptions)
- func (d *Document) SearchProgress() (searched, total int)
- func (d *Document) SearchQuery() string
- func (d *Document) SearchResults() []SearchResult
- func (d *Document) Searching() bool
- func (d *Document) SelectedText() string
- func (d *Document) SetAnnotationColor(a Annotation, c color.Color) bool
- func (d *Document) SetAnnotationContents(a Annotation, text string) bool
- func (d *Document) SetMetadata(m Metadata) bool
- func (d *Document) SetShowLinkBorders(show bool)
- func (d *Document) SetTool(t Tool)
- func (d *Document) SetViewMode(mode ViewMode)
- func (d *Document) ShowAnnotation(a Annotation)
- func (d *Document) ShowAttachments(show bool)
- func (d *Document) ShowComments(show bool)
- func (d *Document) ShowLinkBorders() bool
- func (d *Document) ShowOutline(show bool)
- func (d *Document) ShowPage(page int)
- func (d *Document) ShowSearchResult(i int)
- func (d *Document) Tool() Tool
- func (d *Document) Undo()
- func (d *Document) ViewMode() ViewMode
- func (d *Document) ViewSettings() ViewSettings
- func (d *Document) Zoom(scale float64)
- func (d *Document) ZoomToFit()
- func (d *Document) ZoomToFitHorizontal()
- func (d *Document) ZoomToFitVertical()
- type DocumentCallbackFn
- type Highlight
- type Link
- type Metadata
- type OutlineItem
- type Page
- type Permissions
- type Rect
- type RenderOptions
- type SearchOptions
- type SearchResult
- type Source
- func (s *Source) Annotations(page int) ([]Annotation, error)
- func (s *Source) Attachments() []Attachment
- func (s *Source) Bound(page int) (image.Rectangle, error)
- func (s *Source) Close() error
- func (s *Source) Encrypted() bool
- func (s *Source) Links(page int) ([]Link, error)
- func (s *Source) Metadata() Metadata
- func (s *Source) Outline() []OutlineItem
- func (s *Source) PageByLabel(label string) (int, bool)
- func (s *Source) PageCount() int
- func (s *Source) PageLabel(page int) string
- func (s *Source) PageText(ctx context.Context, page int) (string, error)
- func (s *Source) Permissions() Permissions
- func (s *Source) RenderPage(page int, dpi float64) (image.Image, error)
- func (s *Source) RenderPageContext(ctx context.Context, page int, dpi float64) (image.Image, error)
- func (s *Source) RenderPageOptions(ctx context.Context, page int, dpi float64, opt RenderOptions) (image.Image, error)
- func (s *Source) Search(ctx context.Context, query string, opt SearchOptions) ([]SearchResult, error)
- func (s *Source) SearchPage(ctx context.Context, page int, query string, opt SearchOptions) ([]SearchResult, error)
- func (s *Source) ViewSettings() ViewSettings
- type SourceOptions
- type Thumbnail
- func (t *Thumbnail) CreateRenderer() fyne.WidgetRenderer
- func (t *Thumbnail) Selected() bool
- func (t *Thumbnail) SetImage(theImage image.Image)
- func (t *Thumbnail) SetMinimumSize(size fyne.Size)
- func (t *Thumbnail) SetSelected(selected bool)
- func (t *Thumbnail) SetTitle(title string)
- func (t *Thumbnail) Tapped(_ *fyne.PointEvent)
- type Tool
- type ViewMode
- type ViewSettings
Examples ¶
Constants ¶
const ( // PermPrint allows printing; without PermPrintFaithful only in a // quality that does not serve as a copy of the document. PermPrint = Permissions(cera.PermPrint) // PermModify allows changing the content of the document. PermModify = Permissions(cera.PermModify) // PermCopy allows copying text and graphics out of the document. PermCopy = Permissions(cera.PermCopy) // PermAnnotate allows adding and changing annotations, and filling in // form fields. PermAnnotate = Permissions(cera.PermAnnotate) // PermFillForms allows filling in form fields, also without // PermAnnotate. PermFillForms = Permissions(cera.PermFillForms) // PermExtract allowed extracting text and graphics for accessibility; // PDF 2.0 always allows that. PermExtract = Permissions(cera.PermExtract) // PermAssemble allows inserting, deleting and rotating pages. PermAssemble = Permissions(cera.PermAssemble) // PermPrintFaithful allows printing in full quality. PermPrintFaithful = Permissions(cera.PermPrintFaithful) // AllPermissions is every permission: those of a PDF that is not // encrypted, or that was opened with the owner password. AllPermissions = Permissions(cera.AllPermissions) )
The permissions of an encrypted PDF.
const ThumbnailMinimumDimension = float32(100)
ThumbnailMinimumDimension is the default width and height of a thumbnail.
Variables ¶
var ( // ErrPassword is returned (wrapped, test with errors.Is) when a PDF is // encrypted and the password given does not open it: no password and // a wrong one alike. Ask for one and open it again with // [OpenSourceWithPassword]. ErrPassword = cera.ErrPassword // ErrUnsupportedEncryption is returned (wrapped) for a PDF encrypted in // a way that cannot be read: a security handler other than the // standard one, such as certificates. No password opens it. ErrUnsupportedEncryption = cera.ErrUnsupportedEncryption )
Functions ¶
func NewImageFromMemory ¶
func NewImageFromMemory(contents []byte, pageNumber int, documentCallbacks ...DocumentCallbackFn) (image.Image, error)
NewImageFromMemory renders page pageNumber (0-based) of the PDF in contents at 144 dpi. documentCallbacks are called with the opened Source before rendering.
Example ¶
package main
import (
"fmt"
"os"
pdf "github.com/timzifer/fyne-pdf"
)
func main() {
contents, err := os.ReadFile("example.pdf")
if err != nil {
panic(err)
}
img, err := pdf.NewImageFromMemory(contents, 0)
if err != nil {
panic(err)
}
fmt.Println(img.Bounds().Size())
}
Output:
Types ¶
type Annotation ¶ added in v0.7.0
type Annotation struct {
// Page is the index (0-based) of the page, Index the position of
// the annotation in the page's /Annots: together they name it.
Page, Index int
// Subtype is the kind: "Text" (a note), "Highlight", "FreeText",
// "Ink", "Square", "Stamp", ...
Subtype string
// Contents is the text of the annotation.
Contents string
// Author is who made it, Subject what it is about.
Author, Subject string
// Created and Modified are zero when the annotation does not say.
Created, Modified time.Time
// Color is the colour of the annotation, nil if it has none.
Color color.Color
// Bounds is the rectangle of the annotation; Rects the areas of
// text a Highlight, Underline, Squiggly or StrikeOut marks.
Bounds Rect
Rects []Rect
// Icon names the icon of a note or stamp: "Note", "Comment",
// "Approved", ...
Icon string
// State and StateModel are the review state a reply sets on the
// annotation it replies to: "Accepted" of "Review", ...
State, StateModel string
// ReplyTo is the Index of the annotation this one replies to, -1
// if none. Group says that it is a part of that one rather than a
// reply: viewers show both as one.
ReplyTo int
Group bool
// Popup is the window that shows the text, nil for none.
Popup *AnnotationPopup
// File is the file a FileAttachment annotation embeds, nil for
// other annotations.
File *Attachment
}
Annotation is a markup annotation of a page: a note, a highlight, a shape, a stamp and the like, with what it says about itself. The geometry is in points (1/72 inch) of the displayed page from its top left.
type AnnotationPopup ¶ added in v0.7.0
type AnnotationPopup struct {
Bounds Rect
// Open says that the window is shown at first.
Open bool
}
AnnotationPopup is the window of an annotation that shows its text.
type Attachment ¶ added in v0.7.0
type Attachment struct {
// Name is the file name, Description what the document says
// about the file.
Name string
Description string
// MIME is the media type, such as "application/xml"; empty if the
// document gives none.
MIME string
// Size is the size in bytes as the document states it, -1 if it
// does not.
Size int64
// Created and Modified are zero when the document does not say.
Created, Modified time.Time
// Relationship is what the file is to the document
// (/AFRelationship): "Source", "Data", "Alternative",
// "Supplement", ...; empty if it does not say. The XML of an
// e-invoice is "Alternative" or "Data".
Relationship string
// Page and Index name the file attachment annotation that holds
// the file, as in [Annotation]; Page is -1 for a file of the
// document itself.
Page, Index int
// contains filtered or unexported fields
}
Attachment is a file a PDF embeds: the XML of an e-invoice, source data, another PDF.
func (Attachment) Open ¶ added in v0.7.0
func (a Attachment) Open() (io.ReadCloser, error)
Open returns the content of the file, decoded and, in an encrypted PDF, decrypted. It fails once the PDF it comes from is closed; the widget closes a PDF also when it shows a changed version of it, so take the files from Document.Attachments when they are needed.
type Destination ¶ added in v0.7.0
type Destination struct {
// Page is the index (0-based) of the page.
Page int
// Fit is the kind of view: "XYZ" shows X, Y at the top left at
// Zoom; "Fit" fits the page into the view, "FitH" its width with
// Y at the top, "FitV" its height with X at the left, "FitR" Rect;
// "FitB", "FitBH" and "FitBV" are treated as their plain kinds.
Fit string
// X and Y are the point of the page at the top left of the view;
// NaN keeps the current one, or for Y, the top of the page.
X, Y float64
// Zoom is the zoom of XYZ (1 is 100 %); 0 keeps the current one.
Zoom float64
// Rect is the area to fit into the view for FitR.
Rect Rect
}
Destination is a view of a page, as outline entries and links lead to, in points (1/72 inch) of the displayed page from its top left.
type Document ¶
type Document struct {
widget.BaseWidget
// BackgroundColor fills the area around the pages. If nil, the
// theme's separator color is used.
BackgroundColor color.Color
// SaveCallback, if set, shows a save button in the toolbar that calls
// it. Call Refresh after changing it.
SaveCallback func()
// OnError is called on the main goroutine when a page cannot be
// rendered. If nil, the error is logged.
OnError func(page int, err error)
// OnSearchChanged is called on the main goroutine when the search
// changes: results found, the current result, the search done or
// cleared. See [Document.Search].
OnSearchChanged func()
// PasswordCallback, if set, is asked for the password of an
// encrypted PDF that needs one: retry is false the first time and
// true after a wrong password. It is called again until the
// password opens the PDF or it returns ok false. If nil,
// LoadFromMemory asks with a dialog on the widget's window.
PasswordCallback func(retry bool) (password string, ok bool)
// OnChanged is called when the annotations were changed, a change
// was undone or redone, or the document was saved: when
// Modified, CanUndo or CanRedo may say something else.
OnChanged func()
// OnToolChanged is called when the tool changes, also by the
// toolbar's button for selecting text.
OnToolChanged func()
// Author is the author of the annotations made with the tools.
Author string
// Fonts supplies the fonts a PDF names but does not embed, see
// [SourceOptions]; PDFs loaded after it is set use it. If nil,
// such fonts are drawn with the stand-ins cera has built in.
Fonts cera.FontProvider
// AnnotationColor is the colour of the annotations made with the
// tools; if nil, yellow for highlights and notes, red for
// drawings and shapes, black for underlines and strikethroughs.
AnnotationColor color.Color
// OnLoaded is called on the main goroutine when a PDF has been
// loaded: by LoadFromMemory, or once the password asked for by
// its dialog has been entered.
OnLoaded func()
// FollowViewSettings opens a PDF the way it asks, see
// [Document.ViewSettings]: at the page and view it names, with
// all pages one below the other for "OneColumn" and with the
// outline panel for "UseOutlines". NewDocument sets it; an
// application that restores a view of its own switches it off.
// The settings are applied before OnLoaded is called, so that
// what OnLoaded does with the view stays.
FollowViewSettings bool
// OnLinkTapped, if set, is called when a link on a page is
// tapped; returning true means it handled the link. Otherwise the
// widget goes to the link's destination, opens its URI in the
// browser, or follows its named action; a link to another PDF it
// has the system open after the user agreed in a dialog. It never
// starts a program, runs a script or sends a form.
OnLinkTapped func(Link) bool
// OnLinkHovered, if set, is called when the pointer comes over a
// link on a page, and with nil when it leaves one, to say what
// the link does: see [Link.Description].
OnLinkHovered func(*Link)
// OnPrint, if set, is called by a link that asks to print the
// document; without it such links do nothing.
OnPrint func()
// Dir is the directory the loaded PDF comes from, for its links to
// other PDFs that are named relative to it. The widget loads PDFs
// from memory and does not know it; set it with the PDF.
Dir string
// HighlightColor fills the search results on the pages,
// CurrentHighlightColor the current one. If nil, translucent
// yellow and orange are used.
HighlightColor, CurrentHighlightColor color.Color
// contains filtered or unexported fields
}
Document is a PDF viewer widget: a page view with a toolbar for zooming and a thumbnail strip for navigation. Create it with NewDocument.
The page view shows one page at a time or, see Document.SetViewMode, all pages one below the other. It supports the usual viewer gestures: Ctrl+wheel (Cmd on macOS) zooms around the pointer, dragging pans, a double tap switches between the fitted page and 100 %; showing one page, scrolling on past its top or bottom turns it. Once clicked, it takes the keyboard focus: Page Up/Down and Space scroll by a screen, Home/End go to the first and last page, the arrow keys scroll (Left/Right go to the previous and next page while the pages fit horizontally), Ctrl +/-/0 zoom. On a touch screen (Android, iOS) two fingers pinch to zoom around the point between them; on Windows a pinch on a precision touchpad zooms as Ctrl+wheel does.
Document.Search finds text in the background and highlights the results on the pages; F3 and Shift+F3 go to the next and previous one.
Pages are rendered in the background, those in view first; the resolution of the main view follows the zoom level. Methods must be called from the Fyne main goroutine (or before the app runs).
func NewDocument ¶
func NewDocument() *Document
NewDocument creates an empty viewer. Load a PDF with Document.LoadFromMemory.
func (*Document) Annotations ¶ added in v0.7.0
func (d *Document) Annotations(page int) []Annotation
Annotations returns the markup annotations of page read so far; they are read in the background after loading.
func (*Document) Attachments ¶ added in v0.7.0
func (d *Document) Attachments() []Attachment
Attachments returns the files of the loaded PDF the attachments panel lists: those of the document, then those of its file attachment annotations as far as they are read; they are read in the background after loading.
func (*Document) AttachmentsShown ¶ added in v0.7.0
AttachmentsShown reports whether the attachments panel is shown.
func (*Document) CanGoBack ¶ added in v0.7.0
CanGoBack reports whether there is a view to go back to: one left by a link, an outline entry or Document.GoTo.
func (*Document) CanGoForward ¶ added in v0.7.0
CanGoForward reports whether there is a view gone back from.
func (*Document) CanUndo ¶ added in v0.7.0
CanUndo and CanRedo report whether there is a change to undo or redo.
func (*Document) ClearSearch ¶ added in v0.6.0
func (d *Document) ClearSearch()
ClearSearch ends the search and removes its highlights.
func (*Document) ClearSelection ¶ added in v0.7.0
func (d *Document) ClearSelection()
ClearSelection clears the text selection.
func (*Document) Close ¶
Close releases the loaded PDF and stops pending renders. Pages already shown stay visible.
func (*Document) CommentsShown ¶ added in v0.7.0
CommentsShown reports whether the comments panel is shown.
func (*Document) Contents ¶ added in v0.7.0
Contents returns the file of the document as it is now, with the changes made to it.
func (*Document) CopySelection ¶ added in v0.7.0
CopySelection copies the selected text to the clipboard. It reports false, and copies nothing, when there is no selection or the document does not allow copying (PermCopy).
func (*Document) CreateRenderer ¶
func (d *Document) CreateRenderer() fyne.WidgetRenderer
func (*Document) CurrentPage ¶
CurrentPage returns the index (0-based) of the page shown in the main view. Showing all pages, it is the page at the centre of the view, or the one last gone to with Document.ShowPage or a key until the view is scrolled.
func (*Document) CurrentSearchResult ¶ added in v0.6.0
CurrentSearchResult returns the index of the current result into SearchResults, or -1 if there is none.
func (*Document) DeleteAnnotation ¶ added in v0.7.0
func (d *Document) DeleteAnnotation(a Annotation) bool
DeleteAnnotation removes a, one of Document.Annotations, from the document, with its popup and its replies; the Delete key removes the annotation selected in the comments panel or on the page.
func (*Document) GoBack ¶ added in v0.7.0
GoBack returns to the view that was shown before the last jump — its page, zoom and place; Alt+Left in the page view. It reports whether there was one.
func (*Document) GoForward ¶ added in v0.7.0
GoForward returns to the view Document.GoBack left; Alt+Right in the page view. It reports whether there was one.
func (*Document) GoTo ¶ added in v0.7.0
func (d *Document) GoTo(dest Destination)
GoTo shows dest: it makes its page current, and zooms and scrolls as its kind of view says. A destination out of range is ignored. Document.GoBack returns to the view left.
func (*Document) GoToLabel ¶ added in v0.7.0
GoToLabel goes to the first page with label, the number the document prints on it, keeping the zoom. It reports false if no page has the label.
func (*Document) LoadFromMemory ¶
LoadFromMemory opens the PDF in contents and shows its first page. A previously loaded PDF is closed. Pages are rendered in the background.
An encrypted PDF that needs a password is opened with the one Document.PasswordCallback returns; if it gives up, the error wraps ErrPassword. Without a callback, LoadFromMemory shows a password dialog on the widget's window and returns nil at once: the PDF is loaded, and Document.OnLoaded called, when the right password is entered; the dialog asks again after a wrong one, and cancelling it leaves the previous PDF. A widget not on a window returns an error wrapping ErrPassword.
func (*Document) Metadata ¶ added in v0.7.0
Metadata returns the metadata of the loaded PDF, see Source.Metadata.
func (*Document) Modified ¶ added in v0.7.0
Modified reports whether the document was changed since it was loaded or saved.
func (*Document) MoveAnnotation ¶ added in v0.7.0
func (d *Document) MoveAnnotation(a Annotation, dx, dy float64) bool
MoveAnnotation moves a, one of Document.Annotations, by dx, dy points of the page. Text markup — highlights, underlines, strikethroughs — belongs to its text and is not moved. Dragging the selected annotation with ToolNone moves it, too.
func (*Document) NextSearchResult ¶ added in v0.6.0
func (d *Document) NextSearchResult()
NextSearchResult makes the result after the current one current, wrapping around to the first, and scrolls to it. Without a current result, it goes to the first result at or after the current page.
func (*Document) Outline ¶ added in v0.7.0
func (d *Document) Outline() []OutlineItem
Outline returns the outline of the loaded PDF, see Source.Outline.
func (*Document) OutlineShown ¶ added in v0.7.0
OutlineShown reports whether the outline panel is shown.
func (*Document) PageLabel ¶ added in v0.7.0
PageLabel returns the label of page (0-based) of the loaded PDF, see Source.PageLabel.
func (*Document) PageSize ¶ added in v0.7.0
PageSize returns the width and height of page (0-based) in points (1/72 inch), as it is displayed; 0, 0 for a page the loaded PDF does not have.
func (*Document) Permissions ¶ added in v0.7.0
func (d *Document) Permissions() Permissions
Permissions returns what the loaded PDF allows, see Source.Permissions; 0 if none is loaded.
func (*Document) PreviousSearchResult ¶ added in v0.6.0
func (d *Document) PreviousSearchResult()
PreviousSearchResult makes the result before the current one current, wrapping around to the last, and scrolls to it. Without a current result, it goes to the last result at or before the current page.
func (*Document) Redo ¶ added in v0.7.0
func (d *Document) Redo()
Redo makes the change undone last again; Ctrl+Y or Ctrl+Shift+Z.
func (*Document) Resize ¶
Resize lays out the widget. While the page is fitted to the view (after ShowPage or one of the ZoomToFit methods), the fit follows the new size.
func (*Document) Save ¶ added in v0.7.0
Save writes the document with its changes to w. A document that is signed or encrypted is written as it was loaded followed by incremental updates, which keep its signatures valid and it encrypted; others are written as a new file. Afterwards the document counts as unchanged.
func (*Document) Search ¶ added in v0.6.0
func (d *Document) Search(query string, opt SearchOptions)
Search finds query in the document, in the background: pages from the current one to the end first, then those before it. The results are highlighted on the pages as they are found; the first one at or after the current page becomes the current result, and the view scrolls to it. OnSearchChanged reports the progress. An empty query, like Document.ClearSearch, ends the search and removes the highlights. Loading another document ends it, too.
func (*Document) SearchProgress ¶ added in v0.6.0
SearchProgress returns the number of pages searched so far and the number of pages to search.
func (*Document) SearchQuery ¶ added in v0.6.0
SearchQuery returns the query of the last search, "" after ClearSearch.
func (*Document) SearchResults ¶ added in v0.6.0
func (d *Document) SearchResults() []SearchResult
SearchResults returns the results found so far, sorted by page and in reading order on a page. While the search runs, results of pages before the page it started at are inserted in front of those found earlier.
func (*Document) Searching ¶ added in v0.6.0
Searching reports whether the search is still going through the pages.
func (*Document) SelectedText ¶ added in v0.7.0
SelectedText returns the selected text; "" if there is none.
func (*Document) SetAnnotationColor ¶ added in v0.7.0
func (d *Document) SetAnnotationColor(a Annotation, c color.Color) bool
SetAnnotationColor sets the colour of a, one of Document.Annotations.
func (*Document) SetAnnotationContents ¶ added in v0.7.0
func (d *Document) SetAnnotationContents(a Annotation, text string) bool
SetAnnotationContents sets the text of a, one of Document.Annotations.
func (*Document) SetMetadata ¶ added in v0.7.0
SetMetadata sets the metadata of the document: its information dictionary and its XMP packet, which then say the same. Empty fields and zero dates are removed. The XMP packet is m.XMP, or the one the document has when m.XMP is nil, with the properties that mirror the fields changed and what else it holds kept; start from Document.Metadata to change single fields.
It is a change like those of the annotation tools: a step of undo, written by Document.Save. It reports false if the document does not allow it, with the error through OnError.
func (*Document) SetShowLinkBorders ¶ added in v0.7.0
SetShowLinkBorders sets whether the main view draws the borders link annotations ask for, such as the coloured boxes around the links of LaTeX documents made with hyperref (see RenderOptions.LinkBorders). Off by default; thumbnails never show them. The pages in view are rendered again, showing the old images until then.
func (*Document) SetTool ¶ added in v0.7.0
SetTool sets what dragging and tapping on the pages do: pan them (ToolNone, the default), select text (ToolSelect; the toolbar has a button for it), or make annotations (ToolHighlight, ToolNote, ToolInk, ...): they are written to the document at once, Undo and Redo take them back, Save writes the document with them. Switching clears the text selection.
func (*Document) SetViewMode ¶ added in v0.5.0
SetViewMode switches between showing one page at a time (ViewSinglePage, the default) and all pages one below the other (ViewContinuous). The current page stays in view, as do the zoom and the fit. The toolbar has a button for it, too.
func (*Document) ShowAnnotation ¶ added in v0.7.0
func (d *Document) ShowAnnotation(a Annotation)
ShowAnnotation goes to a, one of Document.Annotations, marks it on its page and in the comments panel, and shows its text and replies beside it.
func (*Document) ShowAttachments ¶ added in v0.7.0
ShowAttachments shows or hides the attachments panel beside the pages: a list of the files the document embeds, each with a button to save it. It is hidden at first; the toolbar has a button for it while the document has such files. The widget never opens a file.
func (*Document) ShowComments ¶ added in v0.7.0
ShowComments shows or hides the comments panel beside the pages: a list of the annotations of the document with their authors, dates and replies. It is hidden at first; the toolbar has a button for it once the document is found to have annotations.
func (*Document) ShowLinkBorders ¶ added in v0.7.0
ShowLinkBorders reports whether the main view draws the borders of links, see Document.SetShowLinkBorders.
func (*Document) ShowOutline ¶ added in v0.7.0
ShowOutline shows or hides the outline panel beside the pages. It is hidden at first; the toolbar has a button for it while the PDF has an outline. A PDF without one hides it.
func (*Document) ShowPage ¶
ShowPage makes page (0-based) current. Showing one page at a time, it shows page fitted into the view. Showing all pages, it scrolls to the top of page and keeps the zoom, or the fit applied to page.
func (*Document) ShowSearchResult ¶ added in v0.6.0
ShowSearchResult makes result i (an index into SearchResults) the current result, highlighted in CurrentHighlightColor, and scrolls the view so it is visible: to its page and, unless it is in view already, with the result at the centre of the view.
func (*Document) Undo ¶ added in v0.7.0
func (d *Document) Undo()
Undo undoes the last change of the annotations; Ctrl+Z.
func (*Document) ViewSettings ¶ added in v0.7.0
func (d *Document) ViewSettings() ViewSettings
ViewSettings returns how the loaded PDF asks to be opened, see Source.ViewSettings.
func (*Document) Zoom ¶
Zoom sets the zoom factor; 1 shows the page at roughly its physical size. The factor is clamped to 0.2 to 4.
func (*Document) ZoomToFit ¶
func (d *Document) ZoomToFit()
ZoomToFit scales the current page so it fits completely into the view; showing all pages, it also scrolls to the top of that page. The fit is kept when the view is resized, until the zoom is changed otherwise; the same holds for ZoomToFitVertical and ZoomToFitHorizontal.
func (*Document) ZoomToFitHorizontal ¶
func (d *Document) ZoomToFitHorizontal()
ZoomToFitHorizontal scales the current page to the width of the view.
func (*Document) ZoomToFitVertical ¶
func (d *Document) ZoomToFitVertical()
ZoomToFitVertical scales the current page to the height of the view.
type DocumentCallbackFn ¶
type DocumentCallbackFn func(src *Source)
DocumentCallbackFn is called with the opened Source before rendering, see NewImageFromMemory.
type Highlight ¶ added in v0.6.0
Highlight marks an area of a Page, such as a search result: a rectangle in the units of Page.PageSize (at Scale 1, origin at the top left of the page), filled with Color over the page image. Use a translucent color to keep the text readable.
type Link ¶ added in v0.7.0
type Link struct {
// Rects are the areas that react, in points (1/72 inch) of the
// displayed page from its top left.
Rects []Rect
// Dest is where the link leads in the document; nil for one that
// leads elsewhere.
Dest *Destination
// URI is the address of a link to the web (or mailto:).
URI string
// External is set for a link out of the document: to another PDF
// (Action "GoToR"), which the widget opens after the user agreed, to a
// file embedded in this or another one ("GoToE", see Embedded) or to a
// file or program ("Launch"), which it never opens. File names it.
External bool
File string
// Embedded is the way to the target of a "GoToE" link, from File, or
// from this document when File is empty: the names of embedded files,
// each inside the one before.
Embedded []string
// NamedAction is the name of a command for the viewer: "NextPage",
// "PrevPage", "FirstPage" and "LastPage", which the widget follows,
// "GoBack" and "GoForward" (see [Document.GoBack]), "Print" (see
// Document.OnPrint), or one it does not know.
NamedAction string
// Action is the type of the action the link was read from: "GoTo",
// "GoToR", "GoToE", "Launch", "URI", "Named", or one that is only
// reported and never done: "JavaScript", "SubmitForm", "Hide", ... It
// is empty for a plain destination.
Action string
// contains filtered or unexported fields
}
Link is a link on a page: an area that leads to a place in the document, to a URI or to another file, or that asks the viewer to do something. Link.Description says in words what it does.
func (*Link) Contains ¶ added in v0.7.0
Contains reports whether the point x, y (in points of the displayed page) is on the link.
func (*Link) Description ¶ added in v0.7.0
Description says in words what following the link does, for a tooltip or a status line: "Go to page 12", "Open https://example.com/". For a link the widget does not follow — one that runs a script, starts a program or submits a form — it says what the link would do.
type Metadata ¶ added in v0.5.0
type Metadata struct {
Title, Author, Subject, Keywords, Creator, Producer string
// Created and Modified are zero when absent or not a date.
Created, Modified time.Time
// Trapped is "True", "False", "Unknown" or "".
Trapped string
// Custom holds the other string entries of /Info, by key as written
// in the document ("Department", ...).
Custom map[string]string
// XMP is the catalog's /Metadata stream, decoded but not parsed; nil if
// there is none.
XMP []byte
}
Metadata is what a document says about itself: its document information dictionary (/Info), decoded, and its XMP metadata stream.
type OutlineItem ¶ added in v0.7.0
type OutlineItem struct {
Title string
// Dest is where the entry leads in the document; nil for an entry
// that leads elsewhere (URI, External) or nowhere, such as a
// heading of its children.
Dest *Destination
// URI is the address of an entry that leads to the web.
URI string
// External is set for an entry that leads to another file or
// launches an application; File names it. The widget does not
// follow it.
External bool
File string
// Open says that the children are shown at first.
Open bool
// Bold and Italic are the style of the title, Color its colour
// (black by default).
Bold, Italic bool
Color color.RGBA
Children []OutlineItem
}
OutlineItem is an entry of the document outline, the bookmarks a viewer shows in a side panel.
type Page ¶
type Page struct {
widget.BaseWidget
Scale float64
BackgroundColor color.Color
// contains filtered or unexported fields
}
Page displays a single rendered page image at Page.PageSize multiplied by Scale, which is also its minimum size. A larger widget centres the page on BackgroundColor. The image is scaled to the page size, so it can be rendered at any resolution; the aspect ratio is kept. Highlights, see Page.SetHighlights, are drawn over the image.
func NewPageWithImage ¶
NewPageWithImage creates a Page showing img.
func (*Page) CreateRenderer ¶
func (p *Page) CreateRenderer() fyne.WidgetRenderer
func (*Page) Highlights ¶ added in v0.6.0
Highlights returns the highlights drawn over the page.
func (*Page) PageSize ¶
PageSize returns the size of the page at Scale 1. Unless set with Page.SetPageSize, this is the size of the page image in pixels.
func (*Page) SetHighlights ¶ added in v0.6.0
SetHighlights replaces the highlights drawn over the page; nil removes them.
func (*Page) SetPageSize ¶
SetPageSize sets the size of the page at Scale 1, independent of the resolution of the image.
type Permissions ¶ added in v0.7.0
type Permissions uint32
Permissions are what the author of an encrypted PDF allows a reader who opened it with the user password. Rendering and text extraction work regardless; whether to print or copy is the application's decision.
type Rect ¶ added in v0.6.0
type Rect struct {
X0, Y0, X1, Y1 float64
}
Rect is a rectangle on a page in points (1/72 inch) of the page as it is displayed: origin at the top left corner, y down, /Rotate and /UserUnit applied, like Source.Bound.
type RenderOptions ¶ added in v0.7.0
type RenderOptions struct {
// LinkBorders draws the borders link annotations ask for (/Border,
// /BS with /C), such as the coloured boxes hyperref puts around the
// links of LaTeX documents. Acrobat and Firefox draw them, Chrome and
// Preview do not; off by default.
LinkBorders bool
}
RenderOptions changes how Source.RenderPageOptions draws a page.
type SearchOptions ¶ added in v0.6.0
type SearchOptions struct {
// MatchCase tells upper and lower case apart.
MatchCase bool
// WholeWord matches the query only where it neither continues a word
// before nor after it.
WholeWord bool
// IgnoreDiacritics finds "resume" in "résumé" and reads compatibility
// characters as what they stand for, such as "2" for "²".
IgnoreDiacritics bool
}
SearchOptions control how a query is matched. The zero value matches case-insensitively anywhere in a word.
type SearchResult ¶ added in v0.6.0
type SearchResult struct {
// Page is the index (0-based) of the page.
Page int
// Text is the text found, Prefix and Suffix up to 32 characters of the
// text before and after it, for a result list. White space in them is
// one space.
Prefix, Text, Suffix string
// Rects cover the text found, one per line it spans.
Rects []Rect
}
SearchResult is a place on a page where the query was found.
func (SearchResult) Bounds ¶ added in v0.6.0
func (r SearchResult) Bounds() Rect
Bounds returns the smallest rectangle around the rects of r.
type Source ¶
type Source struct {
// contains filtered or unexported fields
}
Source is an opened PDF. All methods are safe for concurrent use: cera only allows interpreting pages of a document from one goroutine at a time, hence the mutex. A single page is still rasterized by cera on all cores.
func OpenSource ¶
OpenSource parses the PDF in contents. An encrypted PDF that needs a password returns an error wrapping ErrPassword.
Example ¶
package main
import (
"fmt"
"os"
pdf "github.com/timzifer/fyne-pdf"
)
func main() {
contents, err := os.ReadFile("example.pdf")
if err != nil {
panic(err)
}
src, err := pdf.OpenSource(contents)
if err != nil {
panic(err)
}
defer func() { _ = src.Close() }()
fmt.Println("pages:", src.PageCount())
fmt.Println("title:", src.Metadata().Title)
img, err := src.RenderPage(0, 300)
if err != nil {
panic(err)
}
fmt.Println("size:", img.Bounds().Size())
}
Output:
func OpenSourceWith ¶ added in v0.7.0
func OpenSourceWith(contents []byte, opt SourceOptions) (*Source, error)
OpenSourceWith parses the PDF in contents with options. The errors are those of OpenSourceWithPassword.
func OpenSourceWithPassword ¶ added in v0.7.0
OpenSourceWithPassword parses the encrypted PDF in contents with password: its user password, or its owner password, which lifts the restrictions of Source.Permissions. A wrong password returns an error wrapping ErrPassword, encryption that cannot be read one wrapping ErrUnsupportedEncryption.
func (*Source) Annotations ¶ added in v0.7.0
func (s *Source) Annotations(page int) ([]Annotation, error)
Annotations returns the markup annotations of page (0-based) in the order of its /Annots, leaving out hidden ones but replies: those a comments panel lists. Links, form fields and popup windows are not markup annotations.
func (*Source) Attachments ¶ added in v0.7.0
func (s *Source) Attachments() []Attachment
Attachments returns the files the PDF embeds, nil for a PDF without, or after Close. The files of file attachment annotations are on their pages, see Annotation.File.
func (*Source) Bound ¶
Bound returns the visible area of page (0-based) in points (72 dpi), with /Rotate and /UserUnit already applied.
func (*Source) Close ¶
Close releases the document. Afterwards all methods return an error or zero pages. Closing more than once is allowed.
func (*Source) Encrypted ¶ added in v0.7.0
Encrypted reports whether the PDF is encrypted; false after Close.
func (*Source) Links ¶ added in v0.7.0
Links returns the links of page (0-based) in the order of the page's annotations, leaving out hidden ones.
func (*Source) Metadata ¶
Metadata returns the document's metadata, or the zero Metadata after Close. A missing or damaged /Info gives empty fields.
func (*Source) Outline ¶ added in v0.7.0
func (s *Source) Outline() []OutlineItem
Outline returns the entries at the top of the document outline, nil for a PDF without one, or after Close.
func (*Source) PageByLabel ¶ added in v0.7.0
PageByLabel returns the first page (0-based) with label, and false if no page has it, as in a document without page labels.
func (*Source) PageLabel ¶ added in v0.7.0
PageLabel returns the label of page (0-based): the number the document prints on it, as "iv", "12" or "A-3". It is empty for a document without page labels, for a page before the first that has one, and after Close.
func (*Source) PageText ¶ added in v0.6.0
PageText returns the text of page (0-based) in reading order: lines separated by a line break, blocks of text by an empty line.
func (*Source) Permissions ¶ added in v0.7.0
func (s *Source) Permissions() Permissions
Permissions returns what the PDF allows: AllPermissions if it is not encrypted or was opened with the owner password, else what its author granted; 0 after Close.
func (*Source) RenderPage ¶
RenderPage renders page (0-based) at the given resolution onto a white background. If rendering takes longer than 15 seconds, the partially drawn image is returned without an error.
func (*Source) RenderPageContext ¶
RenderPageContext is like Source.RenderPage, but stops early and returns ctx.Err() when ctx is cancelled.
func (*Source) RenderPageOptions ¶ added in v0.7.0
func (s *Source) RenderPageOptions(ctx context.Context, page int, dpi float64, opt RenderOptions) (image.Image, error)
RenderPageOptions is like Source.RenderPageContext, with options.
func (*Source) Search ¶ added in v0.6.0
func (s *Source) Search(ctx context.Context, query string, opt SearchOptions) ([]SearchResult, error)
Search returns the places of query in the whole document, page by page, as Source.SearchPage finds them. Pages whose text cannot be read are skipped; their errors are returned joined, with the results of the other pages. When ctx ends, Search returns the results so far and ctx.Err().
func (*Source) SearchPage ¶ added in v0.6.0
func (s *Source) SearchPage(ctx context.Context, page int, query string, opt SearchOptions) ([]SearchResult, error)
SearchPage returns the places of query on page (0-based), in reading order and not overlapping. Runs of white space in the text and the query match one space, and words broken across lines by a hyphen are found joined. An empty query finds nothing.
func (*Source) ViewSettings ¶ added in v0.7.0
func (s *Source) ViewSettings() ViewSettings
ViewSettings returns how the PDF asks to be opened; the defaults after Close.
type SourceOptions ¶ added in v0.7.0
type SourceOptions struct {
// Password opens an encrypted PDF, see [OpenSourceWithPassword].
Password string
// Fonts supplies the fonts the PDF names but does not embed: those
// of the machine (github.com/timzifer/cera/fonts/system), CJK fonts
// (github.com/timzifer/cera/fonts/cjk), or several as a
// [cera.FontProviders]. If nil, such fonts are drawn with the
// stand-ins cera has built in.
Fonts cera.FontProvider
}
SourceOptions say how OpenSourceWith opens a PDF.
type Thumbnail ¶
type Thumbnail struct {
widget.BaseWidget
OnTapped func()
// contains filtered or unexported fields
}
Thumbnail is a tappable page preview with a title below it.
func (*Thumbnail) CreateRenderer ¶
func (t *Thumbnail) CreateRenderer() fyne.WidgetRenderer
func (*Thumbnail) SetMinimumSize ¶
SetMinimumSize sets the size of the preview image area.
func (*Thumbnail) SetSelected ¶
SetSelected highlights the thumbnail, e.g. for the page currently shown.
func (*Thumbnail) Tapped ¶
func (t *Thumbnail) Tapped(_ *fyne.PointEvent)
type Tool ¶ added in v0.7.0
type Tool int
Tool is what dragging on the pages does, see Document.SetTool.
const ( // ToolHighlight, ToolUnderline and ToolStrikeOut mark the text a drag // selects, or the word a double click does. ToolHighlight Tool = iota + ToolSelect + 1 ToolUnderline ToolStrikeOut // ToolNote places a note where the page is tapped and asks for its // text. ToolNote // ToolInk draws what a drag draws. ToolInk // ToolRect, ToolEllipse and ToolLine draw a rectangle, an ellipse or // a line from where a drag starts to where it ends. ToolRect ToolEllipse ToolLine // ToolFreeText places a text box where the page is tapped, or over // the area a drag spans, and asks for its text. ToolFreeText )
The annotation tools: see Document.SetTool.
type ViewMode ¶ added in v0.5.0
type ViewMode int
ViewMode selects how the main view of a Document shows the pages.
type ViewSettings ¶ added in v0.7.0
type ViewSettings struct {
// Open is where to start; nil if the PDF does not say. It is nil as
// well for anything that would run or lead out of the document: a
// script, an address, another file.
Open *Destination
// PageMode is what is shown with the pages: "UseNone" (nothing, the
// default), "UseOutlines" (the outline), "UseThumbs" (thumbnails),
// "FullScreen", "UseOC" (the layers) or "UseAttachments".
PageMode string
// PageLayout is how the pages are laid out: "SinglePage" (one at a
// time, the default), "OneColumn" (all pages one below the other),
// "TwoColumnLeft" and "TwoColumnRight" (two columns), "TwoPageLeft"
// and "TwoPageRight" (two pages at a time).
PageLayout string
// RightToLeft says that the document reads from right to left: the
// pages of a spread run from the right.
RightToLeft bool
// DisplayDocTitle says that the title bar is to show the title of
// the document ([Metadata.Title]) rather than the name of its file.
DisplayDocTitle bool
}
ViewSettings is how a PDF asks to be opened.
Source Files
¶
- annotation_edit.go
- annotations.go
- attachments.go
- comments.go
- doc.go
- document.go
- document_search.go
- editing.go
- gestures.go
- image.go
- layout.go
- linkactions.go
- links.go
- modifiers_other.go
- outline.go
- page.go
- pagelabels.go
- pinch.go
- pinch_other.go
- properties.go
- render.go
- search.go
- selection.go
- source.go
- thumbnail.go
- tools.go
- view.go
- viewsettings.go