Anotacions i Formularis
Anotacions i formularis
Aspose.PDF FOSS per a .NET us ofereix accés complet de lectura/escriptura a les anotacions PDF
i als camps interactius d’AcroForm. El punt d’entrada principal per a les anotacions ésPage.Annotations (un AnnotationCollection), mentre que els camps del formulari s’accedeixen
a través de Document.Form. Ambdós subsistemes funcionen completament en memòria i no requereixen
cap clau de llicència.
Afegint anotacions
AnnotationCollection exposa mètodes d’ajuda tipats per a cada tipus d’anotació estàndard. Cada mètode accepta un Rectangle que defineix la posició de l’anotació a la pàgina, més paràmetres específics del tipus.
using var doc = Document.Open(pdfBytes);
var page = doc.Pages[1];
// Text (sticky-note) annotation
page.Annotations.AddTextAnnotation(
new Rectangle(72, 720, 200, 740),
contents: "Review this paragraph",
title: "Editor",
open: true);
// Highlight annotation
page.Annotations.AddHighlightAnnotation(
new Rectangle(72, 680, 300, 700),
quadPoints: null,
color: new double[] { 1, 1, 0 });
// Free-text annotation (rendered directly on the page)
page.Annotations.AddFreeTextAnnotation(
new Rectangle(72, 640, 350, 660),
contents: "Inline note",
fontName: "Helvetica",
fontSize: 10,
color: new double[] { 0, 0, 0 });
using var ms = new MemoryStream();
doc.Save(ms);Anotacions d’enllaç i accions
Els enllaços combinen un rectangle clicable amb un PdfAction. La biblioteca admet accions URI, GoTo, JavaScript, Named i Launch.
using var doc = Document.Open(pdfBytes);
var page = doc.Pages[1];
// URI link
var uriAction = PdfAction.CreateUri("https://aspose.com");
page.Annotations.AddLinkAnnotation(
new Rectangle(50, 700, 200, 720), uriAction);
// GoTo link (jump to page 3)
page.Annotations.AddLinkAnnotation(
new Rectangle(50, 660, 200, 680),
destinationPage: 3,
destRect: new Rectangle(0, 0, 612, 792));
// JavaScript link
var jsAction = PdfAction.CreateJavaScript("app.alert('Hello');");
page.Annotations.AddLinkAnnotation(
new Rectangle(50, 620, 200, 640), jsAction);
doc.Save("links.pdf");Per llegir un enllaç de tornada després d’obrir un PDF desat, converteix l’anotació a LinkAnnotation i inspecciona la seva propietat Uri o resol el diccionari d’acció mitjançant PdfAction.Create.
Anotacions de marcatge i formes
Les anotacions de marcat (highlight, underline, strikeout) marquen el text existent. Les anotacions de forma (square, circle, line, ink) dibuixen geometria a la pàgina.
var page = doc.Pages[1];
// Underline
page.Annotations.AddUnderlineAnnotation(
new Rectangle(72, 600, 300, 620),
quadPoints: null,
color: new double[] { 1, 0, 0 });
// Square
page.Annotations.AddSquareAnnotation(
new Rectangle(72, 540, 200, 580),
borderColor: new double[] { 0, 0, 1 },
fillColor: null,
lineWidth: 1.5);
// Line
page.Annotations.AddLineAnnotation(
new Rectangle(72, 500, 300, 520),
x1: 72, y1: 510, x2: 300, y2: 510,
color: new double[] { 0, 0.5, 0 },
lineWidth: 2);
// Ink (freehand)
page.Annotations.AddInkAnnotation(
new Rectangle(72, 440, 200, 480),
inkPaths: new[] { new double[] { 80, 450, 120, 470, 160, 450 } },
color: new double[] { 0.5, 0, 0.5 },
lineWidth: 1);Anotacions de segell
Les anotacions de segell superposen una imatge o una icona predefinida a una pàgina.
var stamp = new StampAnnotation(doc);
// Configure stamp properties, then add to page
page.Annotations.Add(stamp);Aplanament d’anotacions
Crida Flatten() a qualsevol anotació per incrustar la seva aparença visual al flux de contingut de la pàgina i eliminar-la de la llista d’anotacions interactives.
foreach (var annot in doc.Pages[1].Annotations)
{
annot.Flatten();
}El patró Visitor amb AnnotationSelector
AnnotationSelector implementa el patró visitor perquè puguis filtrar les anotacions per tipus sense fer conversions manuals.
var selector = new AnnotationSelector();
doc.Pages[1].Accept(selector);
// selector.Selected now contains all annotations on page 1
foreach (var annot in selector.Selected)
{
// Process each annotation by type
}Passeu una instància d’anotació tipada al constructor per filtrar només aquest tipus:
var linkFilter = new AnnotationSelector(new LinkAnnotation(page, Rectangle.Empty));
page.Accept(linkFilter);
// linkFilter.Selected contains only LinkAnnotation instancesCamps de formulari interactius
Accediu als camps AcroForm a través de Document.Form. La classe Form exposa operacions de lectura/escriptura a nivell de camp i admet l’exportació JSON.
using var doc = Document.Open(pdfBytes);
// Enumerate all fields
foreach (var field in doc.Form.Fields)
{
Console.WriteLine($"{field.FullName}: {field.Value}");
}Les subclasses de Field inclouen TextBoxField, CheckboxField, RadioButtonField, ComboBoxField, ListBoxField, ChoiceField i SignatureField.
Exportació de dades del formulari a JSON
WidgetAnnotation proporciona ExportToJson sobrecàrregues per a serialitzar dades de camp a un flux o ruta de fitxer. Un paràmetre opcional ExportFieldsToJsonOptions controla el format de sortida.
using var doc = Document.Open(pdfBytes);
var widget = (WidgetAnnotation)doc.Pages[1].Annotations[1];
using var jsonStream = new MemoryStream();
widget.ExportToJson(jsonStream);Consells i bones pràctiques
- Sempre especifiqueu coordenades explícites
Rectangleen unitats d’espai d’usuari del PDF (1/72 polzada). - Utilitzeu
AddLinkAnnotationamb unPdfActionper a la màxima flexibilitat — URI, GoTo, JavaScript i accions Named són compatibles. - Cridau
Flatten()abans de distribuir un PDF si voleu que les anotacions apareguin en visualitzadors no interactius. - Accediu als camps del formulari mitjançant
Document.Form.Fieldsen lloc d’iterar les anotacions de la pàgina — la col·lecció de formularis gestiona la agrupació de camps entre pàgines. - Deseu i torneu a obrir el document per verificar la fidelitat de les anotacions en el viatge d’anada i tornada, especialment per a accions personalitzades.
Problemes comuns
| Issue | Cause | Fix |
|---|---|---|
| L’anotació no és visible després de desar | El rectangle té àrea zero o està fora dels límits de la pàgina | Verifiqueu que les coordenades caiguin dins de la pàgina MediaBox |
LinkAnnotation.Uri retorna null | L’enllaç utilitza una acció GoTo o JavaScript, no una acció URI | Resolgueu el diccionari d’acció mitjançant PdfAction.Create i comproveu ActionType |
| El valor del camp del formulari és una cadena buida | El camp existeix però no té l’entrada /V | Comproveu que field.Value no sigui nul abans del processament |
Flatten() llança | L’anotació no té referència /P (pàgina) | Assegureu-vos que l’anotació s’hagi afegit a través de Page.Annotations |
PMF
Com afegeixo un enllaç a una pàgina PDF?
Utilitzeu page.Annotations.AddLinkAnnotation(rect, PdfAction.CreateUri(url)) per crear un enllaç URI clicable al rectangle especificat.
Puc llegir els valors dels camps del formulari d’un PDF existent?
Sí. Obriu el document amb Document.Open, després iteri Document.Form.Fields i llegiu la propietat Value a cada Field.
Quins tipus d’anotació admet la biblioteca?
La biblioteca admet text, text lliure, enllaç, ressaltat, subratllat, ratllat,
quadrat, cercle, línia, tinta, segell, cursor, adjunció de fitxer, so, polígon,
polilínia, giny, marca d’aigua i anotacions 3D. Tots els tipus estan disponibles a través de
AnnotationCollection mètodes d’ajuda o construcció directa.
Com filtro les anotacions per tipus?
Utilitzeu AnnotationSelector amb una anotació de plantilla tipada. Crideu page.Accept(selector)
i inspeccioneu selector.Selected per a anotacions coincidents.
Puc aplanar només anotacions específiques?
Sí. Crida Flatten() a instàncies individuals de Annotation en lloc d’iterar tota la col·lecció.
Resum de la referència de l’API
| Class / Method | Description |
|---|---|
AnnotationCollection | Col·lecció tipada a cada Page; proporciona assistents Add* per a tots els tipus d’anotació |
AnnotationCollection.AddTextAnnotation | Afegeix una anotació de nota adhesiva |
AnnotationCollection.AddLinkAnnotation | Afegeix un enllaç amb URI, destinació de pàgina o acció personalitzada |
AnnotationCollection.AddHighlightAnnotation | Afegeix una anotació de ressaltat de text |
AnnotationCollection.AddInkAnnotation | Afegeix una anotació de dibuix a mà alçada |
AnnotationCollection.AddSquareAnnotation | Afegeix una anotació de forma rectangular |
AnnotationCollection.AddCircleAnnotation | Afegeix una anotació de forma el·líptica |
AnnotationCollection.AddLineAnnotation | Afegeix una anotació de línia |
Annotation.Flatten | Incrusta l’aparença de l’anotació al contingut de la pàgina |
Annotation.Accept | Despatxa a la sobrecàrrega tipada AnnotationSelector.Visit |
AnnotationSelector | Visitant que recull anotacions per tipus |
LinkAnnotation | Subclasse d’anotació que porta un URI o una acció |
TextAnnotation | Anotació de nota adhesiva |
InkAnnotation | Anotació de dibuix a mà alçada amb camins de traç |
StampAnnotation | Anotació de superposició d’imatge o icona |
WidgetAnnotation.ExportToJson | Serialitza les dades del camp de formulari a JSON |
Form | Fasada d’AcroForm; enumera i manipula camps |
Field | Classe base per a camps de formulari (TextBoxField, CheckboxField, etc.) |
CheckboxField | Camp de formulari de casella de selecció |
TextBoxField | Camp d’entrada de text d’una o diverses línies |
ComboBoxField | Camp de selecció desplegable |
RadioButtonField | Camp de grup de botons d’opció |
AnnotationType | Enumeració de tipus d’anotació |
PdfAction.CreateUri | Fàbrica d’accions d’enllaç URI |
PdfAction.CreateJavaScript | Fàbrica d’accions JavaScript |