Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Last active March 12, 2020 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aspose-com-gists/63473b1ba28e09e229cfbf4430eabd8a to your computer and use it in GitHub Desktop.
Save aspose-com-gists/63473b1ba28e09e229cfbf4430eabd8a to your computer and use it in GitHub Desktop.
Aspose.PDF for .NET
Gist for Aspose.PDF for .NET
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures();
Document doc = new Document(dataDir + "blank.pdf");
using (Facades.PdfFileSignature pdfSign = new Facades.PdfFileSignature())
{
pdfSign.BindPdf(doc);
// Sign with certificate selection in the windows certificate store
System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser);
store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);
// Manually chose the certificate in the store
System.Security.Cryptography.X509Certificates.X509Certificate2Collection sel = System.Security.Cryptography.X509Certificates.X509Certificate2UI.SelectFromCollection(store.Certificates, null, null, System.Security.Cryptography.X509Certificates.X509SelectionFlag.SingleSelection);
Aspose.Pdf.Forms.ExternalSignature externalSignature = new Aspose.Pdf.Forms.ExternalSignature(sel[0]);
pdfSign.SignatureAppearance = dataDir + "demo.png";
pdfSign.Sign(1, "Reason", "Contact", "Location", true, new System.Drawing.Rectangle(100, 100, 200, 200), externalSignature);
pdfSign.Save(dataDir + "externalSignature2.pdf");
}
using (Facades.PdfFileSignature pdfSign = new Facades.PdfFileSignature(new Document(dataDir + "externalSignature2.pdf")))
{
IList<string> sigNames = pdfSign.GetSignNames();
for (int index = 0; index <= sigNames.Count - 1; index++)
{
if (!pdfSign.VerifySigned(sigNames[index]) || !pdfSign.VerifySignature(sigNames[index]))
{
throw new ApplicationException("Not verified");
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures();
File.Copy(dataDir + "blank.pdf", dataDir + "externalSignature1.pdf", true);
using (FileStream fs = new FileStream(dataDir + "externalSignature1.pdf", FileMode.Open, FileAccess.ReadWrite))
{
using (Document doc = new Document(fs))
{
SignatureField field1 = new SignatureField(doc.Pages[1], new Rectangle(100, 400, 10, 10));
// Sign with certificate selection in the windows certificate store
System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser);
store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);
// Manually chose the certificate in the store
System.Security.Cryptography.X509Certificates.X509Certificate2Collection sel = System.Security.Cryptography.X509Certificates.X509Certificate2UI.SelectFromCollection(store.Certificates, null, null, System.Security.Cryptography.X509Certificates.X509SelectionFlag.SingleSelection);
Aspose.Pdf.Forms.ExternalSignature externalSignature = new Aspose.Pdf.Forms.ExternalSignature(sel[0])
{
Authority = "Me",
Reason = "Reason",
ContactInfo = "Contact"
};
field1.PartialName = "sig1";
doc.Form.Add(field1, 1);
field1.Sign(externalSignature);
doc.Save();
}
}
using (PdfFileSignature pdfSign = new PdfFileSignature(new Document(dataDir + "externalSignature1.pdf")))
{
IList<string> sigNames = pdfSign.GetSignNames();
for (int index = 0; index <= sigNames.Count - 1; index++)
{
if (!pdfSign.VerifySigned(sigNames[index]) || !pdfSign.VerifySignature(sigNames[index]))
{
throw new ApplicationException("Not verified");
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Annotations();
Document doc = new Document();
Page pdfPage = doc.Pages.Add();
System.Drawing.Rectangle drect = new System.Drawing.Rectangle();
drect.Height = (int)pdfPage.Rect.Height;
drect.Width = (int)pdfPage.Rect.Width;
drect.X = 0;
drect.Y = 0;
Aspose.Pdf.Rectangle arect = Aspose.Pdf.Rectangle.FromRect(drect);
IList<Point[]> inkList = new List<Point[]>();
Aspose.Pdf.Point[] arrpt = new Aspose.Pdf.Point[3];
inkList.Add(arrpt);
arrpt[0] = new Aspose.Pdf.Point(100, 800);
arrpt[1] = new Aspose.Pdf.Point(200, 800);
arrpt[2] = new Aspose.Pdf.Point(200, 700);
InkAnnotation ia = new InkAnnotation(pdfPage, arect, inkList);
ia.Title = "XXX";
ia.Color = Aspose.Pdf.Color.LightBlue; // (GetColorFromString(stroke.InkColor));
ia.CapStyle = CapStyle.Rounded;
Border border = new Border(ia);
border.Width = 25;
ia.Opacity = 0.5;
pdfPage.Annotations.Add(ia);
dataDir = dataDir + "AddlnkAnnotation_out.pdf";
// Save output file
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Annotations();
Document doc = new Document(dataDir + "ExtractHighlightedText.pdf");
// Loop through all the annotations
foreach (Annotation annotation in doc.Pages[1].Annotations)
{
// Filter TextMarkupAnnotation
if (annotation is TextMarkupAnnotation)
{
TextMarkupAnnotation highlightedAnnotation = annotation as TextMarkupAnnotation;
// Retrieve highlighted text fragments
TextFragmentCollection collection = highlightedAnnotation.GetMarkedTextFragments();
foreach (TextFragment tf in collection)
{
// Display highlighted text
Console.WriteLine(tf.Text);
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Annotations();
// Open document
Document doc = new Document(dataDir + "AddAnnotation.pdf");
//Create annotation
ScreenAnnotation sa = new ScreenAnnotation(doc.Pages[1], new Rectangle(100, 400, 300, 600), dataDir + "AddSwfFileAsAnnotation.swf");
doc.Pages[1].Annotations.Add(sa);
// Save Doucument
doc.Save(dataDir + "GetResourceOfAnnotation_Out.pdf");
// Open document
Document doc1 = new Document(dataDir + "GetResourceOfAnnotation_Out.pdf");
//Get action of the annotation
RenditionAction action = (doc.Pages[1].Annotations[1] as ScreenAnnotation).Action as RenditionAction;
//Get rendition of the rendition action
Rendition rendition = ((doc.Pages[1].Annotations[1] as ScreenAnnotation).Action as RenditionAction).Rendition;
//Media Clip
MediaClip clip = (rendition as MediaRendition).MediaClip;
FileSpecification data = (clip as MediaClipData).Data;
MemoryStream ms = new MemoryStream();
byte[] buffer = new byte[1024];
int read = 0;
//Data of media are accessible in FileSpecification.Contents
Stream source = data.Contents;
while ((read = source.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
Console.WriteLine(rendition.Name);
Console.WriteLine(action.RenditionOperation);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Annotations();
Document doc = new Document();
doc.Pages.Add();
IList<Point[]> inkList = new List<Point[]>();
LineInfo lineInfo = new LineInfo();
lineInfo.VerticeCoordinate = new float[] { 55, 55, 70, 70, 70, 90, 150, 60 };
lineInfo.Visibility = true;
lineInfo.LineColor = System.Drawing.Color.Red;
lineInfo.LineWidth = 2;
int length = lineInfo.VerticeCoordinate.Length / 2;
Aspose.Pdf.Point[] gesture = new Aspose.Pdf.Point[length];
for (int i = 0; i < length; i++)
{
gesture[i] = new Aspose.Pdf.Point(lineInfo.VerticeCoordinate[2 * i], lineInfo.VerticeCoordinate[2 * i + 1]);
}
inkList.Add(gesture);
InkAnnotation a1 = new InkAnnotation(doc.Pages[1], new Aspose.Pdf.Rectangle(100, 100, 300, 300), inkList);
a1.Subject = "Test";
a1.Title = "Title";
a1.Color = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Green);
Border border = new Border(a1);
border.Width = 3;
border.Effect = BorderEffect.Cloudy;
border.Dash = new Dash(1, 1);
border.Style = BorderStyle.Solid;
doc.Pages[1].Annotations.Add(a1);
dataDir = dataDir + "lnkAnnotationLineWidth_out.pdf";
// Save output file
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Annotations();
Document doc = new Document();
Page page = doc.Pages.Add();
DefaultAppearance da = new DefaultAppearance();
da.TextColor = System.Drawing.Color.Red;
da.FontSize = 10;
FreeTextAnnotation fta = new FreeTextAnnotation(page, new Rectangle(422.25, 645.75, 583.5, 702.75), da);
fta.Intent = FreeTextIntent.FreeTextCallout;
fta.EndingStyle = LineEnding.OpenArrow;
fta.Callout = new Point[]
{
new Point(428.25,651.75), new Point(462.75,681.375), new Point(474,681.375)
};
page.Annotations.Add(fta);
fta.RichText = "<body xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\" xfa:APIVersion=\"Acrobat:11.0.23\" xfa:spec=\"2.0.2\" style=\"color:#FF0000;font-weight:normal;font-style:normal;font-stretch:normal\"><p dir=\"ltr\"><span style=\"font-size:9.0pt;font-family:Helvetica\">This is a sample</span></p></body>";
doc.Save(dataDir + "SetCalloutProperty.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Annotations();
Document pdfDocument = new Document( dataDir + "AddAnnotation.pdf");
StringBuilder Xfdf = new StringBuilder();
Xfdf.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?><xfdf xmlns=\"http://ns.adobe.com/xfdf/\" xml:space=\"preserve\"><annots>");
CreateXfdf(ref Xfdf);
Xfdf.AppendLine("</annots></xfdf>");
pdfDocument.ImportAnnotationsFromXfdf(new MemoryStream(Encoding.UTF8.GetBytes(Xfdf.ToString())));
pdfDocument.Save(dataDir + "SetCalloutPropertyXFDF.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();
// Initialize HTMLLoadSave Options
HtmlLoadOptions options = new HtmlLoadOptions();
// Set Render to single page property
options.IsRenderToSinglePage = true;
// Load document
Document doc = new Document(dataDir + "HTMLToPDF.html", options);
// Save
doc.Save(dataDir + "RenderContentToSamePage.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();
// Set input file path
string inFile = dataDir + "HTMLSVG.html";
// Set output file path
string outFile = dataDir + "RenderHTMLwithSVGData.pdf";
// Initialize HtmlLoadOptions
HtmlLoadOptions options = new HtmlLoadOptions(Path.GetDirectoryName(inFile));
// Initialize Document object
Document pdfDocument = new Document(inFile, options);
// save
pdfDocument.Save(outFile);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();
// Open Markdown document
Document doc = new Document(dataDir + "sample.md", new MdLoadOptions());
// Save document in PDF format
doc.Save(dataDir + "MarkdownToPDF.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();
using (FileStream fileStream = new FileStream(dataDir + "sample.pcl", FileMode.Open))
using (MemoryStream memoryStream = new MemoryStream())
{
fileStream.CopyTo(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
using (Document document = new Document(memoryStream, new PclLoadOptions()))
{
}
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
HtmlSaveOptions htmlOptions = new HtmlSaveOptions();
// init MarginPartStyle with margin in 20 points
var commonMargin = new SaveOptions.MarginPartStyle(20);
// init MarginPartStyle with margin value auto
var autoMargin = new SaveOptions.MarginPartStyle(true);
// set commonMargin to every page side
htmlOptions.PageMarginIfAny = new HtmlSaveOptions.MarginInfo(commonMargin);
// set horizontal page align to center
htmlOptions.PageMarginIfAny.LeftMarginIfAny = autoMargin;
htmlOptions.PageMarginIfAny.RightMarginIfAny = autoMargin;
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
saveOptions.FixedLayout = (false);
saveOptions.FlowLayoutParagraphFullWidth = true;
Document doc = new Document(dataDir + "FlowLayoutParagraphFullWidth.Pdf");
doc.Save(dataDir + "FlowLayoutParagraphFullWidth_out.html", saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();
string inFile = dataDir + "PDFToHTML.pdf";
string outMainHtmlFile = dataDir + "ExcludeFontResources.pdf";
// Initialize htmlOptions
HtmlSaveOptions htmlOptions = new HtmlSaveOptions
{
ExplicitListOfSavedPages = new[] { 1 },
FixedLayout = true,
CompressSvgGraphicsIfAny = false,
SaveTransparentTexts = true,
SaveShadowedTextsAsTransparentTexts = true,
//FontSavingMode = HtmlSaveOptions.FontSavingModes.DontSave,
ExcludeFontNameList = new[] { "ArialMT", "SymbolMT" },
DefaultFontName = "Comic Sans MS",
UseZOrder = true,
LettersPositioningMethod = HtmlSaveOptions.LettersPositioningMethods.UseEmUnitsAndCompensationOfRoundingErrorsInCss,
PartsEmbeddingMode = HtmlSaveOptions.PartsEmbeddingModes.NoEmbedding,
RasterImagesSavingMode = HtmlSaveOptions.RasterImagesSavingModes.AsEmbeddedPartsOfPngPageBackground,
SplitIntoPages = false
};
Document pdfDocument = new Document(inFile);
// Save
pdfDocument.Save(outMainHtmlFile, htmlOptions);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();
// Load PDF document
Aspose.Pdf.Document doc = new Aspose.Pdf.Document(dataDir + "input.pdf");
// Instantiate PptxSaveOptions instance
Aspose.Pdf.PptxSaveOptions pptx_save = new Aspose.Pdf.PptxSaveOptions();
// Save the output in PPTX format
pptx_save.SlidesAsImages = true;
doc.Save(dataDir + "PDFToPPT_out_.pptx", pptx_save);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();
// Load PDF document
Aspose.Pdf.Document doc = new Aspose.Pdf.Document(dataDir + "input.pdf");
// Instantiate PptxSaveOptions instance
Aspose.Pdf.PptxSaveOptions pptx_save = new Aspose.Pdf.PptxSaveOptions();
//Specify Custom Progress Handler
pptx_save.CustomProgressHandler = ShowProgressOnConsole;
// Save the output in PPTX format
doc.Save(dataDir + "PDFToPPTWithProgressTracking_out_.pptx", pptx_save);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
switch (eventInfo.EventType)
{
case ProgressEventType.TotalProgress:
Console.WriteLine(String.Format("{0} - Conversion progress : {1}% .", DateTime.Now.TimeOfDay, eventInfo.Value.ToString()));
break;
case ProgressEventType.ResultPageCreated:
Console.WriteLine(String.Format("{0} - Result page's {1} of {2} layout created.", DateTime.Now.TimeOfDay, eventInfo.Value.ToString(), eventInfo.MaxValue.ToString()));
break;
case ProgressEventType.ResultPageSaved:
Console.WriteLine(String.Format("{0} - Result page {1} of {2} exported.", DateTime.Now.TimeOfDay, eventInfo.Value.ToString(), eventInfo.MaxValue.ToString()));
break;
case ProgressEventType.SourcePageAnalysed:
Console.WriteLine(String.Format("{0} - Source page {1} of {2} analyzed.", DateTime.Now.TimeOfDay, eventInfo.Value.ToString(), eventInfo.MaxValue.ToString()));
break;
default:
break;
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();
// Load PDF document
Document pdfDocument = new Document(dataDir + "input.pdf");
// Instantiate ExcelSave Option object
Aspose.Pdf.ExcelSaveOptions excelsave = new ExcelSaveOptions();
excelsave.Format = ExcelSaveOptions.ExcelFormat.XLSX;
// Save the output in XLS format
pdfDocument.Save("PDFToXLSX_out.xlsx", excelsave);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();
using (Document pdfDocument = new Document(dataDir + "input.pdf"))
{
using (FileStream imageStream = new FileStream(dataDir + "SetDefaultFontName.png", FileMode.Create))
{
Resolution resolution = new Resolution(300);
PngDevice pngDevice = new PngDevice(resolution);
RenderingOptions ro = new RenderingOptions();
ro.DefaultFontName = "Arial";
pngDevice.RenderingOptions = ro;
pngDevice.Process(pdfDocument.Pages[1], imageStream);
}
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Forms();
// Load source PDF form
Document doc = new Document(dataDir + "input.pdf");
// Flatten Forms
if (doc.Form.Fields.Count() > 0)
{
foreach (var item in doc.Form.Fields)
{
item.Flatten();
}
}
dataDir = dataDir + "FlattenForms_out.pdf";
// Save the updated document
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Forms();
Document doc = new Document(dataDir + "Test2.pdf");
Page page = doc.Pages[1];
IList<Field> fields = page.FieldsInTabOrder;
string s = "";
foreach (Field field in fields)
{
s += field.PartialName;
}
(doc.Form[3] as Field).TabOrder = 1;
(doc.Form[1] as Field).TabOrder = 2;
(doc.Form[2] as Field).TabOrder = 3;
doc.Save(dataDir + "39522_out.pdf");
Document doc1 = new Document(dataDir + "39522_out.pdf");
s = "";
foreach (Field field in doc1.Pages[1].FieldsInTabOrder)
{
s += field.PartialName;
}
string index = "";
foreach (Field field in doc1.Form)
{
index += field.TabOrder;
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Graphs();
Document doc = new Document();
Page page = doc.Pages.Add();
Aspose.Pdf.Drawing.Graph graph = new Aspose.Pdf.Drawing.Graph(300, 300);
page.Paragraphs.Add(graph);
Aspose.Pdf.Drawing.Rectangle rect = new Aspose.Pdf.Drawing.Rectangle(0, 0, 300, 300);
graph.Shapes.Add(rect);
rect.GraphInfo.FillColor = new Aspose.Pdf.Color
{
PatternColorSpace = new GradientAxialShading(Color.Red, Color.Blue)
{
Start = new Point(0, 0),
End = new Point(300, 300)
}
};
doc.Save(dataDir + "AddDrawingWithGradientFill_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Images();
using (Document pdfDocument = new Document())
{
pdfDocument.Pages.Add();
Aspose.Pdf.Image image = new Aspose.Pdf.Image();
image.FileType = ImageFileType.Dicom;
image.ImageStream = new FileStream(dataDir + "0002.dcm", FileMode.Open, FileAccess.Read);
pdfDocument.Pages[1].Paragraphs.Add(image);
// Save output as PDF format
pdfDocument.Save(dataDir + "PdfWithDicomImage_out.pdf");
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Images();
// Open document
Document pdfDocument = new Document(dataDir+ "AddImage.pdf");
// Set coordinates
int lowerLeftX = 100;
int lowerLeftY = 100;
int upperRightX = 200;
int upperRightY = 200;
// Get the page where image needs to be added
Page page = pdfDocument.Pages[1];
// Load image into stream
FileStream imageStream = new FileStream(dataDir + "aspose-logo.jpg", FileMode.Open);
// Add image to Images collection of Page Resources
page.Resources.Images.Add(imageStream);
// Using GSave operator: this operator saves current graphics state
page.Contents.Add(new Aspose.Pdf.Operators.GSave());
// Create Rectangle and Matrix objects
Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY);
Matrix matrix = new Matrix(new double[] { rectangle.URX - rectangle.LLX, 0, 0, rectangle.URY - rectangle.LLY, rectangle.LLX, rectangle.LLY });
// Using ConcatenateMatrix (concatenate matrix) operator: defines how image must be placed
page.Contents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(matrix));
XImage ximage = page.Resources.Images[page.Resources.Images.Count];
// Using Do operator: this operator draws image
page.Contents.Add(new Aspose.Pdf.Operators.Do(ximage.Name));
// Using GRestore operator: this operator restores graphics state
page.Contents.Add(new Aspose.Pdf.Operators.GRestore());
dataDir = dataDir + "AddImage_out.pdf";
// Save updated document
pdfDocument.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Images();
// Retrieve names of all the PDF files in a particular directory
string[] fileEntries = Directory.GetFiles(dataDir, "*.pdf");
// Iterate through all the files entries in array
for (int counter = 0; counter < fileEntries.Length; counter++)
{
//Open document
Document pdfDocument = new Document(fileEntries[counter]);
for (int pageCount = 1; pageCount <= pdfDocument.Pages.Count; pageCount++)
{
using (FileStream imageStream = new FileStream(dataDir + "\\Thumbanils" + counter.ToString() + "_" + pageCount + ".jpg", FileMode.Create))
{
//Create Resolution object
Resolution resolution = new Resolution(300);
//JpegDevice jpegDevice = new JpegDevice(500, 700, resolution, 100);
JpegDevice jpegDevice = new JpegDevice(45, 59, resolution, 100);
//Convert a particular page and save the image to stream
jpegDevice.Process(pdfDocument.Pages[pageCount], imageStream);
//Close stream
imageStream.Close();
}
}
}
// Acrobat objects
Acrobat.CAcroPDDoc pdfDoc;
Acrobat.CAcroPDPage pdfPage;
Acrobat.CAcroRect pdfRect;
Acrobat.CAcroPoint pdfPoint;
AppSettingsReader appSettings = new AppSettingsReader();
string pdfInputPath = appSettings.GetValue("pdfInputPath", typeof(string)).ToString();
string pngOutputPath = appSettings.GetValue("pngOutputPath", typeof(string)).ToString();
string templatePortraitFile = Application.StartupPath + @"\pdftemplate_portrait.gif";
string templateLandscapeFile = Application.StartupPath + @"\pdftemplate_portrait.gif"; ;
try
{
// Get list of files to process from the input path
// Could change to read list from database instead
string[] files = Directory.GetFiles(pdfInputPath, "*.pdf");
for(int n = 0; n<files.Length; n++)
{
string inputFile = files[n].ToString();
string outputFile = pngOutputPath + files[n].Substring(files[n].LastIndexOf(@"\") + 1).Replace(".pdf", ".png");
/* Could skip if thumbnail already exists in output path
FileInfo fi = new FileInfo(inputFile);
if (!fi.Exists) {} */
// Create the document (Can only create the AcroExch.PDDoc object using late-binding)
// Note using VisualBasic helper functions, have to add reference to DLL in
// C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Microsoft.VisualBasic.dll
// Will always be available as .NET framework ships with all
pdfDoc = (Acrobat.CAcroPDDoc) Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.PDDoc", "");
int ret = pdfDoc.Open(inputFile);
if (ret == 0)
{
throw new FileNotFoundException();
}
// Get the number of pages (to be used later if you wanted to store that information)
int pageCount = pdfDoc.GetNumPages();
// Get the first page
pdfPage = (Acrobat.CAcroPDPage) pdfDoc.AcquirePage(0);
pdfPoint = (Acrobat.CAcroPoint) pdfPage.GetSize();
pdfRect = (Acrobat.CAcroRect) Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.Rect", "");
pdfRect.Left = 0;
pdfRect.right = pdfPoint.x;
pdfRect.Top = 0;
pdfRect.bottom = pdfPoint.y;
// Render to clipboard, scaled by 100 percent (ie. original size)
// Even though we want a smaller image, better for us to scale in .NET
// than Acrobat as it would greek out small text
// see http://www.adobe.com/support/techdocs/1dd72.htm
pdfPage.CopyToClipboard(pdfRect, 0, 0, 100);
IDataObject clipboardData = Clipboard.GetDataObject();
if (clipboardData.GetDataPresent(DataFormats.Bitmap))
{
Bitmap pdfBitmap = (Bitmap)clipboardData.GetData(DataFormats.Bitmap);
// Size of generated thumbnail in pixels
int thumbnailWidth = 45;
int thumbnailHeight = 59;
string templateFile;
// Switch between portrait and landscape
if (pdfPoint.x<pdfPoint.y)
{
templateFile = templatePortraitFile;
}
else
{
templateFile = templateLandscapeFile;
// Swap width and height (little trick not using third temp variable)
thumbnailWidth = thumbnailWidth ^ thumbnailHeight;
thumbnailHeight = thumbnailWidth ^ thumbnailHeight;
thumbnailWidth = thumbnailWidth ^ thumbnailHeight;
}
// Load the template graphic
Bitmap templateBitmap = new Bitmap(templateFile);
// Render to small image using the bitmap class
Image pdfImage = pdfBitmap.GetThumbnailImage(thumbnailWidth, thumbnailHeight, null, IntPtr.Zero);
// Create new blank bitmap (+ 7 for template border)
Bitmap thumbnailBitmap = new Bitmap(thumbnailWidth + 7, thumbnailHeight + 7,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
// To overlayout the template with the image, we need to set the transparency
// http://www.sellsbrothers.com/writing/default.aspx?content=dotnetimagerecoloring.htm
templateBitmap.MakeTransparent();
using (Graphics thumbnailGraphics = Graphics.FromImage(thumbnailBitmap))
{
// Draw rendered pdf image to new blank bitmap
thumbnailGraphics.DrawImage(pdfImage, 2, 2, thumbnailWidth, thumbnailHeight);
// Draw template outline over the bitmap (pdf with show through the transparent area)
thumbnailGraphics.DrawImage(templateBitmap, 0, 0);
// Save as .png file
thumbnailBitmap.Save(outputFile, System.Drawing.Imaging.ImageFormat.Png);
Console.WriteLine("Generated thumbnail... {0}", outputFile);
}
pdfDoc.Close();
// Not sure how why it is to do this, but Acrobat is not the best behaved COM object
// see http://blogs.msdn.com/yvesdolc/archive/2004/04/17/115379.aspx
Marshal.ReleaseComObject(pdfPage);
Marshal.ReleaseComObject(pdfRect);
Marshal.ReleaseComObject(pdfDoc);
}
}
}
catch (System.Exception ex)
{
Console.Write(ex.ToString());
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// Initialize Time
var time = DateTime.Now.Ticks;
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Images();
// Open document
Document pdfDocument = new Document(dataDir + "Shrinkimage.pdf");
// Initialize OptimizationOptions
var optimizeOptions = new Pdf.Optimization.OptimizationOptions();
// Set CompressImages option
optimizeOptions.ImageCompressionOptions.CompressImages = true;
// Set ImageQuality option
optimizeOptions.ImageCompressionOptions.ImageQuality = 75;
// Set Imagae Compression Version to fast
optimizeOptions.ImageCompressionOptions.Version = Pdf.Optimization.ImageCompressionVersion.Fast;
// Optimize PDF document using OptimizationOptions
pdfDocument.OptimizeResources(optimizeOptions);
dataDir = dataDir + "FastShrinkImages_out.pdf";
// Save updated document
pdfDocument.Save(dataDir);
Console.WriteLine("Ticks: {0}", DateTime.Now.Ticks - time);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Images();
// Open Document
Document doc = new Document(dataDir + "AddImage.pdf");
// Initialize OptimizationOptions
var optimizationOptions = new Aspose.Pdf.Optimization.OptimizationOptions();
// To optimise image using FlateDecode Compression set optimization options to Flate
optimizationOptions.ImageCompressionOptions.Encoding = ImageEncoding.Flate;
// Set Optimization Options
doc.OptimizeResources(optimizationOptions);
// Save Document
doc.Save(dataDir + "FlateDecodeCompression.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Images();
// Load the source PDF file
Document doc = new Document(dataDir+ "ImageInformation.pdf");
// Define the default resolution for image
int defaultResolution = 72;
System.Collections.Stack graphicsState = new System.Collections.Stack();
// Define array list object which will hold image names
System.Collections.ArrayList imageNames = new System.Collections.ArrayList(doc.Pages[1].Resources.Images.Names);
// Insert an object to stack
graphicsState.Push(new System.Drawing.Drawing2D.Matrix(1, 0, 0, 1, 0, 0));
// Get all the operators on first page of document
foreach (Operator op in doc.Pages[1].Contents)
{
// Use GSave/GRestore operators to revert the transformations back to previously set
Aspose.Pdf.Operators.GSave opSaveState = op as Aspose.Pdf.Operators.GSave;
Aspose.Pdf.Operators.GRestore opRestoreState = op as Aspose.Pdf.Operators.GRestore;
// Instantiate ConcatenateMatrix object as it defines current transformation matrix.
Aspose.Pdf.Operators.ConcatenateMatrix opCtm = op as Aspose.Pdf.Operators.ConcatenateMatrix;
// Create Do operator which draws objects from resources. It draws Form objects and Image objects
Aspose.Pdf.Operators.Do opDo = op as Aspose.Pdf.Operators.Do;
if (opSaveState != null)
{
// Save previous state and push current state to the top of the stack
graphicsState.Push(((System.Drawing.Drawing2D.Matrix)graphicsState.Peek()).Clone());
}
else if (opRestoreState != null)
{
// Throw away current state and restore previous one
graphicsState.Pop();
}
else if (opCtm != null)
{
System.Drawing.Drawing2D.Matrix cm = new System.Drawing.Drawing2D.Matrix(
(float)opCtm.Matrix.A,
(float)opCtm.Matrix.B,
(float)opCtm.Matrix.C,
(float)opCtm.Matrix.D,
(float)opCtm.Matrix.E,
(float)opCtm.Matrix.F);
// Multiply current matrix with the state matrix
((System.Drawing.Drawing2D.Matrix)graphicsState.Peek()).Multiply(cm);
continue;
}
else if (opDo != null)
{
// In case this is an image drawing operator
if (imageNames.Contains(opDo.Name))
{
System.Drawing.Drawing2D.Matrix lastCTM = (System.Drawing.Drawing2D.Matrix)graphicsState.Peek();
// Create XImage object to hold images of first pdf page
XImage image = doc.Pages[1].Resources.Images[opDo.Name];
// Get image dimensions
double scaledWidth = Math.Sqrt(Math.Pow(lastCTM.Elements[0], 2) + Math.Pow(lastCTM.Elements[1], 2));
double scaledHeight = Math.Sqrt(Math.Pow(lastCTM.Elements[2], 2) + Math.Pow(lastCTM.Elements[3], 2));
// Get Height and Width information of image
double originalWidth = image.Width;
double originalHeight = image.Height;
// Compute resolution based on above information
double resHorizontal = originalWidth * defaultResolution / scaledWidth;
double resVertical = originalHeight * defaultResolution / scaledHeight;
// Display Dimension and Resolution information of each image
Console.Out.WriteLine(
string.Format(dataDir + "image {0} ({1:.##}:{2:.##}): res {3:.##} x {4:.##}",
opDo.Name, scaledWidth, scaledHeight, resHorizontal,
resVertical));
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// Initialize Time
var time = DateTime.Now.Ticks;
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Images();
// Open document
Document pdfDocument = new Document(dataDir + "ResizeImage.pdf");
// Initialize OptimizationOptions
var optimizeOptions = new Pdf.Optimization.OptimizationOptions();
// Set CompressImages option
optimizeOptions.ImageCompressionOptions.CompressImages = true;
// Set ImageQuality option
optimizeOptions.ImageCompressionOptions.ImageQuality = 75;
// Set ResizeImage option
optimizeOptions.ImageCompressionOptions.ResizeImages = true;
// Set MaxResolution option
optimizeOptions.ImageCompressionOptions.MaxResolution = 300;
// Optimize PDF document using OptimizationOptions
pdfDocument.OptimizeResources(optimizeOptions);
dataDir = dataDir + "ResizeImages_out.pdf";
// Save updated document
pdfDocument.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Images();
// Instantiate Document object
Document doc = new Document();
// add page to pages collection of PDF file
Aspose.Pdf.Page page = doc.Pages.Add();
// Create an image instance
Aspose.Pdf.Image img = new Aspose.Pdf.Image();
// Set Image Width and Height in Points
img.FixWidth = 100;
img.FixHeight = 100;
// Set image type as SVG
img.FileType = Aspose.Pdf.ImageFileType.Unknown;
// Path for source file
img.File = dataDir + "aspose-logo.jpg";
page.Paragraphs.Add(img);
//Set page properties
page.PageInfo.Width = 800;
page.PageInfo.Height = 800;
dataDir = dataDir + "SetImageSize_out.pdf";
// save resultant PDF file
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Images();
// Open document
Document pdfDocument = new Document(dataDir + "Shrinkimage.pdf");
// Initialize OptimizationOptions
var optimizeOptions = new Pdf.Optimization.OptimizationOptions();
// Set CompressImages option
optimizeOptions.ImageCompressionOptions.CompressImages = true;
// Set ImageQuality option
optimizeOptions.ImageCompressionOptions.ImageQuality = 50;
// Optimize PDF document using OptimizationOptions
pdfDocument.OptimizeResources(optimizeOptions);
dataDir = dataDir + "Shrinkimage_out.pdf";
// Save updated document
pdfDocument.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Images();
// Initialize Document
Aspose.Pdf.Document document = new Document();
document.Pages.Add();
Page page = document.Pages[1];
FileStream imageStream = new FileStream(dataDir + "aspose-logo.jpg", FileMode.Open);
page.Resources.Images.Add(imageStream, ImageFilterType.Flate);
XImage ximage = page.Resources.Images[page.Resources.Images.Count];
page.Contents.Add(new GSave());
// Set coordinates
int lowerLeftX = 0;
int lowerLeftY = 0;
int upperRightX = 600;
int upperRightY = 600;
Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY);
Matrix matrix = new Matrix(new double[] {rectangle.URX - rectangle.LLX, 0, 0, rectangle.URY - rectangle.LLY, rectangle.LLX, rectangle.LLY});
// Using ConcatenateMatrix (concatenate matrix) operator: defines how image must be placed
page.Contents.Add(new ConcatenateMatrix(matrix));
page.Contents.Add(new Do(ximage.Name));
page.Contents.Add(new GRestore());
document.Save(dataDir + "FlateDecodeCompression.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Operators();
string imageFile = dataDir+ "aspose-logo.jpg";
string inFile = dataDir + "DrawXFormOnPage.pdf";
string outFile = dataDir + "blank-sample2_out.pdf";
using (Document doc = new Document(inFile))
{
OperatorCollection pageContents = doc.Pages[1].Contents;
// The sample demonstrates
// GSave/GRestore operators usage
// ContatenateMatrix operator usage to position xForm
// Do operator usage to draw xForm on page
// Wrap existing contents with GSave/GRestore operators pair
// this is to get initial graphics state at the and of existing contents
// otherwise there might remain some undesirable transformations at the end of existing operators chain
pageContents.Insert(1, new Aspose.Pdf.Operators.GSave());
pageContents.Add(new Aspose.Pdf.Operators.GRestore());
// Add save graphics state operator to properly clear graphics state after new commands
pageContents.Add(new Aspose.Pdf.Operators.GSave());
#region create xForm
// Create xForm
XForm form = XForm.CreateNewForm(doc.Pages[1], doc);
doc.Pages[1].Resources.Forms.Add(form);
form.Contents.Add(new Aspose.Pdf.Operators.GSave());
// Define image width and heigh
form.Contents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(200, 0, 0, 200, 0, 0));
// Load image into stream
Stream imageStream = new FileStream(imageFile, FileMode.Open);
// Add image to Images collection of the XForm Resources
form.Resources.Images.Add(imageStream);
XImage ximage = form.Resources.Images[form.Resources.Images.Count];
// Using Do operator: this operator draws image
form.Contents.Add(new Aspose.Pdf.Operators.Do(ximage.Name));
form.Contents.Add(new Aspose.Pdf.Operators.GRestore());
#endregion
pageContents.Add(new Aspose.Pdf.Operators.GSave());
// Place form to the x=100 y=500 coordinates
pageContents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(1, 0, 0, 1, 100, 500));
// Draw form with Do operator
pageContents.Add(new Aspose.Pdf.Operators.Do(form.Name));
pageContents.Add(new Aspose.Pdf.Operators.GRestore());
pageContents.Add(new Aspose.Pdf.Operators.GSave());
// Place form to the x=100 y=300 coordinates
pageContents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(1, 0, 0, 1, 100, 300));
// Draw form with Do operator
pageContents.Add(new Aspose.Pdf.Operators.Do(form.Name));
pageContents.Add(new Aspose.Pdf.Operators.GRestore());
// Restore grahics state with GRestore after the GSave
pageContents.Add(new Aspose.Pdf.Operators.GRestore());
doc.Save(outFile);
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Operators();
// Open document
Document pdfDocument = new Document(dataDir+ "PDFOperators.pdf");
// Set coordinates
int lowerLeftX = 100;
int lowerLeftY = 100;
int upperRightX = 200;
int upperRightY = 200;
// Get the page where image needs to be added
Page page = pdfDocument.Pages[1];
// Load image into stream
FileStream imageStream = new FileStream(dataDir + "PDFOperators.jpg", FileMode.Open);
// Add image to Images collection of Page Resources
page.Resources.Images.Add(imageStream);
// Using GSave operator: this operator saves current graphics state
page.Contents.Add(new Aspose.Pdf.Operators.GSave());
// Create Rectangle and Matrix objects
Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY);
Matrix matrix = new Matrix(new double[] { rectangle.URX - rectangle.LLX, 0, 0, rectangle.URY - rectangle.LLY, rectangle.LLX, rectangle.LLY });
// Using ConcatenateMatrix (concatenate matrix) operator: defines how image must be placed
page.Contents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(matrix));
XImage ximage = page.Resources.Images[page.Resources.Images.Count];
// Using Do operator: this operator draws image
page.Contents.Add(new Aspose.Pdf.Operators.Do(ximage.Name));
// Using GRestore operator: this operator restores graphics state
page.Contents.Add(new Aspose.Pdf.Operators.GRestore());
dataDir = dataDir + "PDFOperators_out.pdf";
// Save updated document
pdfDocument.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Operators();
Document doc = new Document(dataDir+ "RemoveGraphicsObjects.pdf");
Page page = doc.Pages[2];
OperatorCollection oc = page.Contents;
// Used path-painting operators
Operator[] operators = new Operator[] {
new Aspose.Pdf.Operators.Stroke(),
new Aspose.Pdf.Operators.ClosePathStroke(),
new Aspose.Pdf.Operators.Fill()
};
oc.Delete(operators);
doc.Save(dataDir+ "No_Graphics_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures();
string pbxFile = "";
string inFile = dataDir + @"DigitallySign.pdf";
string outFile = dataDir + @"DigitallySign_out.pdf";
using (Document document = new Document(inFile))
{
using (PdfFileSignature signature = new PdfFileSignature(document))
{
PKCS7 pkcs = new PKCS7(pbxFile, "WebSales"); // Use PKCS7/PKCS7Detached objects
DocMDPSignature docMdpSignature = new DocMDPSignature(pkcs, DocMDPAccessPermissions.FillingInForms);
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(100, 100, 200, 100);
// Set signature appearance
signature.SignatureAppearance = dataDir + @"aspose-logo.jpg";
// Create any of the three signature types
signature.Certify(1, "Signature Reason", "Contact", "Location", true, rect, docMdpSignature);
// Save output PDF file
signature.Save(outFile);
}
}
using (Document document = new Document(outFile))
{
using (PdfFileSignature signature = new PdfFileSignature(document))
{
IList<string> sigNames = signature.GetSignNames();
if (sigNames.Count > 0) // Any signatures?
{
if (signature.VerifySigned(sigNames[0] as string)) // Verify first one
{
if (signature.IsCertified) // Certified?
{
if (signature.GetAccessPermissions() == DocMDPAccessPermissions.FillingInForms) // Get access permission
{
// Do something
}
}
}
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures();
Document doc = new Document(dataDir + "blank.pdf");
using (Facades.PdfFileSignature pdfSign = new Facades.PdfFileSignature())
{
pdfSign.BindPdf(doc);
// Sign with certificate selection in the windows certificate store
System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser);
store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);
// Manually chose the certificate in the store
System.Security.Cryptography.X509Certificates.X509Certificate2Collection sel = System.Security.Cryptography.X509Certificates.X509Certificate2UI.SelectFromCollection(store.Certificates, null, null, System.Security.Cryptography.X509Certificates.X509SelectionFlag.SingleSelection);
Aspose.Pdf.Forms.ExternalSignature externalSignature = new Aspose.Pdf.Forms.ExternalSignature(sel[0]);
pdfSign.SignatureAppearance = dataDir + "demo.png";
pdfSign.Sign(1, "Reason", "Contact", "Location", true, new System.Drawing.Rectangle(100, 100, 200, 200), externalSignature);
pdfSign.Save(dataDir + "externalSignature2.pdf");
}
using (Facades.PdfFileSignature pdfSign = new Facades.PdfFileSignature(new Document(dataDir + "externalSignature2.pdf")))
{
IList<string> sigNames = pdfSign.GetSignNames();
for (int index = 0; index <= sigNames.Count - 1; index++)
{
if (!pdfSign.VerifySigned(sigNames[index]) || !pdfSign.VerifySignature(sigNames[index]))
{
throw new ApplicationException("Not verified");
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_SecuritySignatures();
File.Copy(dataDir + "blank.pdf", dataDir + "externalSignature1.pdf", true);
using (FileStream fs = new FileStream(dataDir + "externalSignature1.pdf", FileMode.Open, FileAccess.ReadWrite))
{
using (Document doc = new Document(fs))
{
SignatureField field1 = new SignatureField(doc.Pages[1], new Rectangle(100, 400, 10, 10));
// Sign with certificate selection in the windows certificate store
System.Security.Cryptography.X509Certificates.X509Store store = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser);
store.Open(System.Security.Cryptography.X509Certificates.OpenFlags.ReadOnly);
// Manually chose the certificate in the store
System.Security.Cryptography.X509Certificates.X509Certificate2Collection sel = System.Security.Cryptography.X509Certificates.X509Certificate2UI.SelectFromCollection(store.Certificates, null, null, System.Security.Cryptography.X509Certificates.X509SelectionFlag.SingleSelection);
Aspose.Pdf.Forms.ExternalSignature externalSignature = new Aspose.Pdf.Forms.ExternalSignature(sel[0])
{
Authority = "Me",
Reason = "Reason",
ContactInfo = "Contact"
};
field1.PartialName = "sig1";
doc.Form.Add(field1, 1);
field1.Sign(externalSignature);
doc.Save();
}
}
using (PdfFileSignature pdfSign = new PdfFileSignature(new Document(dataDir + "externalSignature1.pdf")))
{
IList<string> sigNames = pdfSign.GetSignNames();
for (int index = 0; index <= sigNames.Count - 1; index++)
{
if (!pdfSign.VerifySigned(sigNames[index]) || !pdfSign.VerifySignature(sigNames[index]))
{
throw new ApplicationException("Not verified");
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_StampsWatermarks();
// Instantiate Document object
Document doc = new Document();
// Add page to PDF document
Page page = doc.Pages.Add();
// Create FloatingBox object
FloatingBox aBox = new FloatingBox(200, 100);
// Set left position for FloatingBox
aBox.Left = 40;
// Set Top position for FloatingBox
aBox.Top = 80;
// Set the Horizontal alignment for FloatingBox
aBox.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Center;
// Add text fragment to paragraphs collection of FloatingBox
aBox.Paragraphs.Add(new TextFragment("main text"));
// Set border for FloatingBox
aBox.Border = new BorderInfo(BorderSide.All, Aspose.Pdf.Color.Red);
// Add background image
aBox.BackgroundImage = new Image
{
File = dataDir + "aspose-logo.jpg"
};
// Set background color for FloatingBox
aBox.BackgroundColor = Aspose.Pdf.Color.Yellow;
// Add FloatingBox to paragraphs collection of page object
page.Paragraphs.Add(aBox);
// Save the PDF document
doc.Save(dataDir + "AddImageStampAsBackgroundInFloatingBox_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
string dataDir = RunExamples.GetDataDir_AsposePdf_StampsWatermarks();
Document doc = new Document(dataDir + "test.pdf");
StampAnnotation annot = doc.Pages[1].Annotations[3] as StampAnnotation;
TextAbsorber ta = new TextAbsorber();
XForm ap = annot.Appearance["N"];
ta.Visit(ap);
Console.WriteLine(ta.Text);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Tables();
Document doc = new Document(dataDir + "input.pdf");
Stack graphicsState = new Stack();
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap((int)doc.Pages[1].PageInfo.Width, (int)doc.Pages[1].PageInfo.Height);
System.Drawing.Drawing2D.GraphicsPath graphicsPath = new System.Drawing.Drawing2D.GraphicsPath();
// Default ctm matrix value is 1,0,0,1,0,0
System.Drawing.Drawing2D.Matrix lastCTM = new System.Drawing.Drawing2D.Matrix(1, 0, 0, -1, 0, 0);
// System.Drawing coordinate system is top left based, while pdf coordinate system is low left based, so we have to apply the inversion matrix
System.Drawing.Drawing2D.Matrix inversionMatrix = new System.Drawing.Drawing2D.Matrix(1, 0, 0, -1, 0, (float)doc.Pages[1].PageInfo.Height);
System.Drawing.PointF lastPoint = new System.Drawing.PointF(0, 0);
System.Drawing.Color fillColor = System.Drawing.Color.FromArgb(0, 0, 0);
System.Drawing.Color strokeColor = System.Drawing.Color.FromArgb(0, 0, 0);
using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bitmap))
{
gr.SmoothingMode = SmoothingMode.HighQuality;
graphicsState.Push(new System.Drawing.Drawing2D.Matrix(1, 0, 0, 1, 0, 0));
// Process all the contents commands
foreach (Operator op in doc.Pages[1].Contents)
{
Aspose.Pdf.Operators.GSave opSaveState = op as Aspose.Pdf.Operators.GSave;
Aspose.Pdf.Operators.GRestore opRestoreState = op as Aspose.Pdf.Operators.GRestore;
Aspose.Pdf.Operators.ConcatenateMatrix opCtm = op as Aspose.Pdf.Operators.ConcatenateMatrix;
Aspose.Pdf.Operators.MoveTo opMoveTo = op as Aspose.Pdf.Operators.MoveTo;
Aspose.Pdf.Operators.LineTo opLineTo = op as Aspose.Pdf.Operators.LineTo;
Aspose.Pdf.Operators.Re opRe = op as Aspose.Pdf.Operators.Re;
Aspose.Pdf.Operators.EndPath opEndPath = op as Aspose.Pdf.Operators.EndPath;
Aspose.Pdf.Operators.Stroke opStroke = op as Aspose.Pdf.Operators.Stroke;
Aspose.Pdf.Operators.Fill opFill = op as Aspose.Pdf.Operators.Fill;
Aspose.Pdf.Operators.EOFill opEOFill = op as Aspose.Pdf.Operators.EOFill;
Aspose.Pdf.Operators.SetRGBColor opRGBFillColor = op as Aspose.Pdf.Operators.SetRGBColor;
Aspose.Pdf.Operators.SetRGBColorStroke opRGBStrokeColor = op as Aspose.Pdf.Operators.SetRGBColorStroke;
if (opSaveState != null)
{
// Save previous state and push current state to the top of the stack
graphicsState.Push(((System.Drawing.Drawing2D.Matrix)graphicsState.Peek()).Clone());
lastCTM = (System.Drawing.Drawing2D.Matrix)graphicsState.Peek();
}
else if (opRestoreState != null)
{
// Throw away current state and restore previous one
graphicsState.Pop();
lastCTM = (System.Drawing.Drawing2D.Matrix)graphicsState.Peek();
}
else if (opCtm != null)
{
System.Drawing.Drawing2D.Matrix cm = new System.Drawing.Drawing2D.Matrix(
(float)opCtm.Matrix.A,
(float)opCtm.Matrix.B,
(float)opCtm.Matrix.C,
(float)opCtm.Matrix.D,
(float)opCtm.Matrix.E,
(float)opCtm.Matrix.F);
// Multiply current matrix with the state matrix
((System.Drawing.Drawing2D.Matrix)graphicsState.Peek()).Multiply(cm);
lastCTM = (System.Drawing.Drawing2D.Matrix)graphicsState.Peek();
}
else if (opMoveTo != null)
{
lastPoint = new System.Drawing.PointF((float)opMoveTo.X, (float)opMoveTo.Y);
}
else if (opLineTo != null)
{
System.Drawing.PointF linePoint = new System.Drawing.PointF((float)opLineTo.X, (float)opLineTo.Y);
graphicsPath.AddLine(lastPoint, linePoint);
lastPoint = linePoint;
}
else if (opRe != null)
{
System.Drawing.RectangleF re = new System.Drawing.RectangleF((float)opRe.X, (float)opRe.Y, (float)opRe.Width, (float)opRe.Height);
graphicsPath.AddRectangle(re);
}
else if (opEndPath != null)
{
graphicsPath = new System.Drawing.Drawing2D.GraphicsPath();
}
else if (opRGBFillColor != null)
{
fillColor = opRGBFillColor.getColor();
}
else if (opRGBStrokeColor != null)
{
strokeColor = opRGBStrokeColor.getColor();
}
else if (opStroke != null)
{
graphicsPath.Transform(lastCTM);
graphicsPath.Transform(inversionMatrix);
gr.DrawPath(new System.Drawing.Pen(strokeColor), graphicsPath);
graphicsPath = new System.Drawing.Drawing2D.GraphicsPath();
}
else if (opFill != null)
{
graphicsPath.FillMode = FillMode.Winding;
graphicsPath.Transform(lastCTM);
graphicsPath.Transform(inversionMatrix);
gr.FillPath(new System.Drawing.SolidBrush(fillColor), graphicsPath);
graphicsPath = new System.Drawing.Drawing2D.GraphicsPath();
}
else if (opEOFill != null)
{
graphicsPath.FillMode = FillMode.Alternate;
graphicsPath.Transform(lastCTM);
graphicsPath.Transform(inversionMatrix);
gr.FillPath(new System.Drawing.SolidBrush(fillColor), graphicsPath);
graphicsPath = new System.Drawing.Drawing2D.GraphicsPath();
}
}
}
dataDir = dataDir + "ExtractBorder_out.png";
bitmap.Save(dataDir, ImageFormat.Png);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// Create a new document
Document doc = new Document();
// Add page in document
Page page = doc.Pages.Add();
// Initialize new table
Table table = new Table
{
ColumnAdjustment = ColumnAdjustment.AutoFitToContent
};
// Add row in table
Row row = table.Rows.Add();
// Add cell in table
Cell cell = row.Cells.Add("Cell 1 text");
cell = row.Cells.Add("Cell 2 text");
// Get table width
Console.WriteLine(table.GetWidth());
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Tables();
DataTable dt = new DataTable("Employee");
dt.Columns.Add("data", System.Type.GetType("System.String"));
DataRow dr = dt.NewRow();
dr[0] = "<li>Department of Emergency Medicine: 3400 Spruce Street Ground Silverstein Bldg Philadelphia PA 19104-4206</li>";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "<li>Penn Observation Medicine Service: 3400 Spruce Street Ground Floor Donner Philadelphia PA 19104-4206</li>";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "<li>UPHS/Presbyterian - Dept. of Emergency Medicine: 51 N. 39th Street . Philadelphia PA 19104-2640</li>";
dt.Rows.Add(dr);
Document doc = new Document();
doc.Pages.Add();
// Initializes a new instance of the Table
Aspose.Pdf.Table tableProvider = new Aspose.Pdf.Table();
//Set column widths of the table
tableProvider.ColumnWidths = "400 50 ";
// Set the table border color as LightGray
tableProvider.Border = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, 0.5F, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray));
// Set the border for table cells
tableProvider.DefaultCellBorder = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, 0.5F, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray));
Aspose.Pdf.MarginInfo margin = new Aspose.Pdf.MarginInfo();
margin.Top = 2.5F;
margin.Left = 2.5F;
margin.Bottom = 1.0F;
tableProvider.DefaultCellPadding = margin;
tableProvider.ImportDataTable(dt, false, 0, 0, 3, 1, true);
doc.Pages[1].Paragraphs.Add(tableProvider);
doc.Save(dataDir + "HTMLInsideTableCell_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Tables();
// Load existing PDF document
Document pdfDocument = new Document(dataDir + "Table_input2.pdf");
// Create TableAbsorber object to find tables
TableAbsorber absorber = new TableAbsorber();
// Visit second page with absorber
absorber.Visit(pdfDocument.Pages[1]);
// Get copy of table collection
AbsorbedTable[] tables = new AbsorbedTable[absorber.TableList.Count];
absorber.TableList.CopyTo(tables, 0);
// Loop through the copy of collection and removing tables
foreach (AbsorbedTable table in tables)
absorber.Remove(table);
// Save document
pdfDocument.Save(dataDir + "Table2_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Tables();
// Load existing PDF document
Document pdfDocument = new Document(dataDir + "Table_input.pdf");
// Create TableAbsorber object to find tables
TableAbsorber absorber = new TableAbsorber();
// Visit first page with absorber
absorber.Visit(pdfDocument.Pages[1]);
// Get first table on the page
AbsorbedTable table = absorber.TableList[0];
// Remove the table
absorber.Remove(table);
// Save PDF
pdfDocument.Save(dataDir + "Table_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Tables();
// Load existing PDF document
Document pdfDocument = new Document(dataDir + @"Table_input.pdf");
// Create TableAbsorber object to find tables
TableAbsorber absorber = new TableAbsorber();
// Visit first page with absorber
absorber.Visit(pdfDocument.Pages[1]);
// Get first table on the page
AbsorbedTable table = absorber.TableList[0];
// Create new table
Table newTable = new Table();
newTable.ColumnWidths = "100 100 100";
newTable.DefaultCellBorder = new BorderInfo(BorderSide.All, 1F);
Row row = newTable.Rows.Add();
row.Cells.Add("Col 1");
row.Cells.Add("Col 2");
row.Cells.Add("Col 3");
// Replace the table with new one
absorber.Replace(pdfDocument.Pages[1], table, newTable);
// Save document
pdfDocument.Save(dataDir + "TableReplaced_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
var dataDir = RunExamples.GetDataDir_AsposePdf_Tables();
// Create PDF document
Aspose.Pdf.Document doc = new Aspose.Pdf.Document();
// Initializes a new instance of the Table
Aspose.Pdf.Table table = new Aspose.Pdf.Table();
// Set the table border color as LightGray
table.Border = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .5f, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray));
// set the border for table cells
table.DefaultCellBorder = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .5f, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray));
// create a loop to add 10 rows
for (int row_count = 0; row_count < 10; row_count++)
{
// add row to table
Aspose.Pdf.Row row = table.Rows.Add();
row.VerticalAlignment = VerticalAlignment.Center;
row.Cells.Add("Column (" + row_count + ", 1)" + DateTime.Now.Ticks);
row.Cells.Add("Column (" + row_count + ", 2)");
row.Cells.Add("Column (" + row_count + ", 3)");
}
Page tocPage = doc.Pages.Add();
// Add table object to first page of input document
tocPage.Paragraphs.Add(table);
// Save updated document containing table object
doc.Save(dataDir + "43620_ByWords_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
string inXml = "40014.xml";
string outFile = "40014_out.pdf";
Document doc = new Document();
doc.BindXml(dataDir + inXml);
Page page = (Page)doc.GetObjectById("mainSection");
TextSegment segment = (TextSegment)doc.GetObjectById("boldHtml");
segment = (TextSegment)doc.GetObjectById("strongHtml");
doc.Save(dataDir + outFile);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
//Create document with hidden text
Aspose.Pdf.Document doc = new Aspose.Pdf.Document();
Page page = doc.Pages.Add();
TextFragment frag1 = new TextFragment("This is common text.");
TextFragment frag2 = new TextFragment("This is invisible text.");
//Set text property - invisible
frag2.TextState.Invisible = true;
page.Paragraphs.Add(frag1);
page.Paragraphs.Add(frag2);
doc.Save(dataDir + "39400_out.pdf");
doc.Dispose();
//Search text in the document
doc = new Aspose.Pdf.Document(dataDir + "39400_out.pdf");
TextFragmentAbsorber absorber = new TextFragmentAbsorber();
absorber.Visit(doc.Pages[1]);
foreach (TextFragment fragment in absorber.TextFragments)
{
//Do something with fragments
Console.WriteLine("Text '{0}' on pos {1} invisibility: {2} ",
fragment.Text, fragment.Position.ToString(), fragment.TextState.Invisible);
}
doc.Dispose();
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// The path to the output document.
string outFile = dataDir + "AddHTMLOrderedListIntoDocuments_out.pdf";
// Instantiate Document object
Document doc = new Document();
// Instantiate HtmlFragment object with corresponding HTML fragment
HtmlFragment t = new HtmlFragment("`<body style='line-height: 100px;'><ul><li>First</li><li>Second</li><li>Third</li><li>Fourth</li><li>Fifth</li></ul>Text after the list.<br/>Next line<br/>Last line</body>`");
// Add Page in Pages Collection
Page page = doc.Pages.Add();
// Add HtmlFragment inside page
page.Paragraphs.Add(t);
// Save resultant PDF file
doc.Save(outFile);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Instantiate Document object
Document doc = new Document();
// Add a page to pages collection of PDF file
Page page = doc.Pages.Add();
// Instantiate HtmlFragment with HTML contnets
HtmlFragment titel = new HtmlFragment("<fontsize=10><b><i>Table</i></b></fontsize>");
// Set bottom margin information
titel.Margin.Bottom = 10;
// Set top margin information
titel.Margin.Top = 200;
// Add HTML Fragment to paragraphs collection of page
page.Paragraphs.Add(titel);
dataDir = dataDir + "AddHTMLUsingDOM_out.pdf";
// Save PDF file
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
Document doc = new Document();
Page page = doc.Pages.Add();
HtmlFragment html = new HtmlFragment("<fontsize=10><b><i>Aspose.PDF</i></b></fontsize>");
page.Paragraphs.Add(html);
dataDir = dataDir + "HTMLfragmentRectangle_out.pdf";
doc.Save(dataDir);
Console.WriteLine(html.Rectangle.Width);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Instantiate Document object
Document doc = new Document();
// Add a page to pages collection of PDF file
Page page = doc.Pages.Add();
// Instantiate HtmlFragment with HTML contnets
HtmlFragment title = new HtmlFragment("<p style='font-family: Verdana'><b><i>Table contains text</i></b></p>");
//Font-family from 'Verdana' will be reset to 'Arial'
title.TextState = new TextState("Arial");
title.TextState.FontSize = 20;
// Set bottom margin information
title.Margin.Bottom = 10;
// Set top margin information
title.Margin.Top = 400;
// Add HTML Fragment to paragraphs collection of page
page.Paragraphs.Add(title);
// Save PDF file
dataDir = dataDir + "AddHTMLUsingDOMAndOverwrite_out.pdf";
// Save PDF file
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
using (Document pdfDocument = new Document(dataDir + "text_sample4.pdf"))
{
TextFragmentAbsorber absorber = new TextFragmentAbsorber("Lorem ipsum");
pdfDocument.Pages.Accept(absorber);
TextFragment textFragment = absorber.TextFragments[1];
// Create new color with pattern colorspace
textFragment.TextState.ForegroundColor = new Aspose.Pdf.Color()
{
PatternColorSpace = new Aspose.Pdf.Drawing.GradientAxialShading(Color.Red, Color.Blue)
};
textFragment.TextState.Underline = true;
pdfDocument.Save(dataDir + "text_out.pdf");
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ExtractParagraph()
{
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
Document doc = new Document(dataDir + "input.pdf");
Page page = doc.Pages[2];
ParagraphAbsorber absorber = new ParagraphAbsorber();
absorber.Visit(page);
PageMarkup markup = absorber.PageMarkups[0];
foreach (MarkupSection section in markup.Sections)
{
DrawRectangleOnPage(section.Rectangle, page);
foreach (MarkupParagraph paragraph in section.Paragraphs)
{
DrawPolygonOnPage(paragraph.Points, page);
}
}
doc.Save(dataDir + "output_out.pdf");
}
private static void DrawRectangleOnPage(Rectangle rectangle, Page page)
{
page.Contents.Add(new Aspose.Pdf.Operators.GSave());
page.Contents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(1, 0, 0, 1, 0, 0));
page.Contents.Add(new Aspose.Pdf.Operators.SetRGBColorStroke(0, 1, 0));
page.Contents.Add(new Aspose.Pdf.Operators.SetLineWidth(2));
page.Contents.Add(
new Aspose.Pdf.Operators.Re(rectangle.LLX,
rectangle.LLY,
rectangle.Width,
rectangle.Height));
page.Contents.Add(new Aspose.Pdf.Operators.ClosePathStroke());
page.Contents.Add(new Aspose.Pdf.Operators.GRestore());
}
private static void DrawPolygonOnPage(Point[] polygon, Page page)
{
page.Contents.Add(new Aspose.Pdf.Operators.GSave());
page.Contents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(1, 0, 0, 1, 0, 0));
page.Contents.Add(new Aspose.Pdf.Operators.SetRGBColorStroke(0, 0, 1));
page.Contents.Add(new Aspose.Pdf.Operators.SetLineWidth(1));
page.Contents.Add(new Aspose.Pdf.Operators.MoveTo(polygon[0].X, polygon[0].Y));
for (int i = 1; i < polygon.Length; i++)
{
page.Contents.Add(new Aspose.Pdf.Operators.LineTo(polygon[i].X, polygon[i].Y));
}
page.Contents.Add(new Aspose.Pdf.Operators.LineTo(polygon[0].X, polygon[0].Y));
page.Contents.Add(new Aspose.Pdf.Operators.ClosePathStroke());
page.Contents.Add(new Aspose.Pdf.Operators.GRestore());
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Open document
Document pdfDocument = new Document(dataDir + "ExtractTextAll.pdf");
// Create TextAbsorber object to extract text
TextAbsorber textAbsorber = new TextAbsorber();
// Accept the absorber for all the pages
pdfDocument.Pages.Accept(textAbsorber);
// Get the extracted text
string extractedText = textAbsorber.Text;
// Create a writer and open the file
TextWriter tw = new StreamWriter(dataDir + "extracted-text.txt");
// Write a line of text to the file
tw.WriteLine(extractedText);
// Close the stream
tw.Close();
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Open document
Document pdfDocument = new Document(dataDir + "ExtractTextAll.pdf");
// Create TextAbsorber object to extract text
TextAbsorber absorber = new TextAbsorber();
absorber.TextSearchOptions.LimitToPageBounds = true;
absorber.TextSearchOptions.Rectangle = new Aspose.Pdf.Rectangle(100, 200, 250, 350);
// Accept the absorber for first page
pdfDocument.Pages[1].Accept(absorber);
// Get the extracted text
string extractedText = absorber.Text;
// Create a writer and open the file
TextWriter tw = new StreamWriter(dataDir + "extracted-text.txt");
// Write a line of text to the file
tw.WriteLine(extractedText);
// Close the stream
tw.Close();
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Open document
Document pdfDocument = new Document(dataDir + "ExtractTextPage.pdf");
// Create TextAbsorber object to extract text
TextAbsorber textAbsorber = new TextAbsorber();
// Accept the absorber for a particular page
pdfDocument.Pages[1].Accept(textAbsorber);
// Get the extracted text
string extractedText = textAbsorber.Text;
dataDir = dataDir + "extracted-text_out.txt";
// Create a writer and open the file
TextWriter tw = new StreamWriter(dataDir);
// Write a line of text to the file
tw.WriteLine(extractedText);
// Close the stream
tw.Close();
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Open document
Document pdfDocument = new Document( dataDir + "input.pdf");
System.Text.StringBuilder builder = new System.Text.StringBuilder();
// String to hold extracted text
string extractedText = "";
foreach (Page pdfPage in pdfDocument.Pages)
{
using (MemoryStream textStream = new MemoryStream())
{
// Create text device
TextDevice textDevice = new TextDevice();
// Set text extraction options - set text extraction mode (Raw or Pure)
TextExtractionOptions textExtOptions = new
TextExtractionOptions(TextExtractionOptions.TextFormattingMode.Pure);
textDevice.ExtractionOptions = textExtOptions;
// Convert a particular page and save text to the stream
textDevice.Process(pdfPage, textStream);
// Convert a particular page and save text to the stream
textDevice.Process(pdfDocument.Pages[1], textStream);
// Close memory stream
textStream.Close();
// Get text from memory stream
extractedText = Encoding.Unicode.GetString(textStream.ToArray());
}
builder.Append(extractedText);
}
dataDir = dataDir + "input_Text_Extracted_out.txt";
// Save the extracted text in text file
File.WriteAllText(dataDir, builder.ToString());
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// Convert a particular page and save text to the stream
textDevice.Process(pdfDocument.Pages[1], textStream);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Create Document instance
Document doc = new Document();
// Add page to pages collection of PDF
Page page = doc.Pages.Add();
// Create GraphInfo object
Aspose.Pdf.GraphInfo graph = new Aspose.Pdf.GraphInfo();
// Set line width as 2
graph.LineWidth = 2;
// Set the color for graph object
graph.Color = Aspose.Pdf.Color.Red;
// Set dash array value as 3
graph.DashArray = new int[] { 3 };
// Set dash phase value as 1
graph.DashPhase = 1;
// Set footnote line style for page as graph
page.NoteLineStyle = graph;
// Create TextFragment instance
TextFragment text = new TextFragment("Hello World");
// Set FootNote value for TextFragment
text.FootNote = new Note("foot note for test text 1");
// Add TextFragment to paragraphs collection of first page of document
page.Paragraphs.Add(text);
// Create second TextFragment
text = new TextFragment("Aspose.Pdf for .NET");
// Set FootNote for second text fragment
text.FootNote = new Note("foot note for test text 2");
// Add second text fragment to paragraphs collection of PDF file
page.Paragraphs.Add(text);
dataDir = dataDir + "AddFootNote_out.pdf";
// Save resulting PDF document.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
Document doc = new Document();
Page page = doc.Pages.Add();
TextFragment text = new TextFragment("some text");
page.Paragraphs.Add(text);
text.FootNote = new Note();
Aspose.Pdf.Image image = new Aspose.Pdf.Image();
image.File = dataDir + "aspose-logo.jpg";
image.FixHeight = 20;
text.FootNote.Paragraphs.Add(image);
TextFragment footNote = new TextFragment("footnote text");
footNote.TextState.FontSize = 20;
footNote.IsInLineParagraph = true;
text.FootNote.Paragraphs.Add(footNote);
Aspose.Pdf.Table table = new Aspose.Pdf.Table();
table.Rows.Add().Cells.Add().Paragraphs.Add(new TextFragment("Row 1 Cell 1"));
text.FootNote.Paragraphs.Add(table);
dataDir = dataDir + "AddImageAndTable_out.pdf";
// Save resulting PDF document.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Create Document instance
Document doc = new Document();
// Add page to pages collection of PDF
Page page = doc.Pages.Add();
// Create TextFragment instance
TextFragment text = new TextFragment("Hello World");
// Set FootNote value for TextFragment
text.EndNote = new Note("sample End note");
// Specify custom label for FootNote
text.EndNote.Text = " Aspose(2015)";
// Add TextFragment to paragraphs collection of first page of document
page.Paragraphs.Add(text);
dataDir = dataDir + "CreateEndNotes_out.pdf";
// Save resulting PDF document.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Create Document instance
Document doc = new Document();
// Add page to pages collection of PDF
Page page = doc.Pages.Add();
// Create GraphInfo object
Aspose.Pdf.GraphInfo graph = new Aspose.Pdf.GraphInfo();
// Set line width as 2
graph.LineWidth = 2;
// Set the color for graph object
graph.Color = Aspose.Pdf.Color.Red;
// Set dash array value as 3
graph.DashArray = new int[] { 3 };
// Set dash phase value as 1
graph.DashPhase = 1;
// Set footnote line style for page as graph
page.NoteLineStyle = graph;
// Create TextFragment instance
TextFragment text = new TextFragment("Hello World");
// Set FootNote value for TextFragment
text.FootNote = new Note("foot note for test text 1");
// Specify custom label for FootNote
text.FootNote.Text = " Aspose(2015)";
// Add TextFragment to paragraphs collection of first page of document
page.Paragraphs.Add(text);
dataDir = dataDir + "CustomizeFootNoteLabel_out.pdf";
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Create Document instance
Document doc = new Document();
// Add page to pages collection of PDF
Page page = doc.Pages.Add();
// Create GraphInfo object
Aspose.Pdf.GraphInfo graph = new Aspose.Pdf.GraphInfo();
// Set line width as 2
graph.LineWidth = 2;
// Set the color for graph object
graph.Color = Aspose.Pdf.Color.Red;
// Set dash array value as 3
graph.DashArray = new int[] { 3 };
// Set dash phase value as 1
graph.DashPhase = 1;
// Set footnote line style for page as graph
page.NoteLineStyle = graph;
// Create TextFragment instance
TextFragment text = new TextFragment("Hello World");
// Set FootNote value for TextFragment
text.FootNote = new Note("foot note for test text 1");
// Add TextFragment to paragraphs collection of first page of document
page.Paragraphs.Add(text);
// Create second TextFragment
text = new TextFragment("Aspose.Pdf for .NET");
// Set FootNote for second text fragment
text.FootNote = new Note("foot note for test text 2");
// Add second text fragment to paragraphs collection of PDF file
page.Paragraphs.Add(text);
dataDir = dataDir + "CustomLineStyleForFootNote_out.pdf";
// Save resulting PDF document.
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
Aspose.Pdf.Text.Font font = FontRepository.FindFont("Arial");
TextState ts = new TextState();
ts.Font = font;
ts.FontSize = 14;
if (Math.Abs(font.MeasureString("A", 14) - 9.337) > 0.001)
Console.WriteLine("Unexpected font string measure!");
if (Math.Abs(ts.MeasureString("z") - 7.0) > 0.001)
Console.WriteLine("Unexpected font string measure!");
for (char c = 'A'; c <= 'z'; c++)
{
double fnMeasure = font.MeasureString(c.ToString(), 14);
double tsMeasure = ts.MeasureString(c.ToString());
if (Math.Abs(fnMeasure - tsMeasure) > 0.001)
Console.WriteLine("Font and state string measuring doesn't match!");
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
string outputFile = dataDir + "TextBlock_HideShow_MouseOverOut_out.pdf";
// Create sample document with text
Document doc = new Document();
doc.Pages.Add().Paragraphs.Add(new TextFragment("Move the mouse cursor here to display floating text"));
doc.Save(outputFile);
// Open document with text
Document document = new Document(outputFile);
// Create TextAbsorber object to find all the phrases matching the regular expression
TextFragmentAbsorber absorber = new TextFragmentAbsorber("Move the mouse cursor here to display floating text");
// Accept the absorber for the document pages
document.Pages.Accept(absorber);
// Get the first extracted text fragment
TextFragmentCollection textFragments = absorber.TextFragments;
TextFragment fragment = textFragments[1];
// Create hidden text field for floating text in the specified rectangle of the page
TextBoxField floatingField = new TextBoxField(fragment.Page, new Rectangle(100, 700, 220, 740));
// Set text to be displayed as field value
floatingField.Value = "This is the \"floating text field\".";
// We recommend to make field 'readonly' for this scenario
floatingField.ReadOnly = true;
// Set 'hidden' flag to make field invisible on document opening
floatingField.Flags |= AnnotationFlags.Hidden;
// Setting a unique field name isn't necessary but allowed
floatingField.PartialName = "FloatingField_1";
// Setting characteristics of field appearance isn't necessary but makes it better
floatingField.DefaultAppearance = new DefaultAppearance("Helv", 10, System.Drawing.Color.Blue);
floatingField.Characteristics.Background = System.Drawing.Color.LightBlue;
floatingField.Characteristics.Border = System.Drawing.Color.DarkBlue;
floatingField.Border = new Border(floatingField);
floatingField.Border.Width = 1;
floatingField.Multiline = true;
// Add text field to the document
document.Form.Add(floatingField);
// Create invisible button on text fragment position
ButtonField buttonField = new ButtonField(fragment.Page, fragment.Rectangle);
// Create new hide action for specified field (annotation) and invisibility flag.
// (You also may reffer floating field by the name if you specified it above.)
// Add actions on mouse enter/exit at the invisible button field
buttonField.Actions.OnEnter = new HideAction(floatingField, false);
buttonField.Actions.OnExit = new HideAction(floatingField);
// Add button field to the document
document.Form.Add(buttonField);
// Save document
document.Save(outputFile);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
int resolution = 150;
Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(dataDir + "input.pdf");
using (MemoryStream ms = new MemoryStream())
{
PdfConverter conv = new PdfConverter(pdfDocument);
conv.Resolution = new Resolution(resolution, resolution);
conv.GetNextImage(ms, System.Drawing.Imaging.ImageFormat.Png);
Bitmap bmp = (Bitmap)Bitmap.FromStream(ms);
using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp))
{
float scale = resolution / 72f;
gr.Transform = new System.Drawing.Drawing2D.Matrix(scale, 0, 0, -scale, 0, bmp.Height);
for (int i = 0; i < pdfDocument.Pages.Count; i++)
{
Page page = pdfDocument.Pages[1];
// Create TextAbsorber object to find all words
TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(@"[\S]+");
textFragmentAbsorber.TextSearchOptions.IsRegularExpressionUsed = true;
page.Accept(textFragmentAbsorber);
// Get the extracted text fragments
TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;
// Loop through the fragments
foreach (TextFragment textFragment in textFragmentCollection)
{
if (i == 0)
{
gr.DrawRectangle(
Pens.Yellow,
(float)textFragment.Position.XIndent,
(float)textFragment.Position.YIndent,
(float)textFragment.Rectangle.Width,
(float)textFragment.Rectangle.Height);
for (int segNum = 1; segNum <= textFragment.Segments.Count; segNum++)
{
TextSegment segment = textFragment.Segments[segNum];
for (int charNum = 1; charNum <= segment.Characters.Count; charNum++)
{
CharInfo characterInfo = segment.Characters[charNum];
Aspose.Pdf.Rectangle rect = page.GetPageRect(true);
Console.WriteLine("TextFragment = " + textFragment.Text + " Page URY = " + rect.URY +
" TextFragment URY = " + textFragment.Rectangle.URY);
gr.DrawRectangle(
Pens.Black,
(float)characterInfo.Rectangle.LLX,
(float)characterInfo.Rectangle.LLY,
(float)characterInfo.Rectangle.Width,
(float)characterInfo.Rectangle.Height);
}
gr.DrawRectangle(
Pens.Green,
(float)segment.Rectangle.LLX,
(float)segment.Rectangle.LLY,
(float)segment.Rectangle.Width,
(float)segment.Rectangle.Height);
}
}
}
}
}
dataDir = dataDir + "HighlightCharacterInPDF_out.png";
bmp.Save(dataDir, System.Drawing.Imaging.ImageFormat.Png);
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
Document doc = new Document(dataDir + "MultiColumnPdf.pdf");
ParagraphAbsorber absorber = new ParagraphAbsorber();
absorber.Visit(doc);
PageMarkup markup = absorber.PageMarkups[0];
Console.WriteLine("IsMulticolumnParagraphsAllowed == false\r\n");
MarkupSection section = markup.Sections[2];
MarkupParagraph paragraph = section.Paragraphs[section.Paragraphs.Count - 1];
Console.WriteLine("Section at {0} last paragraph text:\r\n", section.Rectangle.ToString());
Console.WriteLine(paragraph.Text);
section = markup.Sections[1];
paragraph = section.Paragraphs[0];
Console.WriteLine("\r\nSection at {0} first paragraph text:\r\n", section.Rectangle.ToString());
Console.WriteLine(paragraph.Text);
markup.IsMulticolumnParagraphsAllowed = true;
Console.WriteLine("\r\nIsMulticolumnParagraphsAllowed == true\r\n");
section = markup.Sections[2];
paragraph = section.Paragraphs[section.Paragraphs.Count - 1];
Console.WriteLine("Section at {0} last paragraph text:\r\n", section.Rectangle.ToString());
Console.WriteLine(paragraph.Text);
section = markup.Sections[1];
paragraph = section.Paragraphs[0];
Console.WriteLine("\r\nSection at {0} first paragraph text:\r\n", section.Rectangle.ToString());
Console.WriteLine(paragraph.Text);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Instantiate document object
Aspose.Pdf.Document doc = new Aspose.Pdf.Document();
// Create a page in the Pdf
Aspose.Pdf.Page page = doc.Pages.Add();
// Instantiate a table object
Aspose.Pdf.Table table1 = new Aspose.Pdf.Table();
// Add the table in paragraphs collection of the desired section
page.Paragraphs.Add(table1);
// Set with column widths of the table
table1.ColumnWidths = "120 270";
// Create MarginInfo object and set its left, bottom, right and top margins
Aspose.Pdf.MarginInfo margin = new Aspose.Pdf.MarginInfo();
margin.Top = 5f;
margin.Left = 5f;
margin.Right = 5f;
margin.Bottom = 5f;
// Set the default cell padding to the MarginInfo object
table1.DefaultCellPadding = margin;
// Create rows in the table and then cells in the rows
Aspose.Pdf.Row row1 = table1.Rows.Add();
// Create an image object
Aspose.Pdf.Image logo = new Aspose.Pdf.Image();
// Specify the image file path
logo.File = dataDir + "aspose-logo.jpg";
// Specify the image Fixed Height
logo.FixHeight = 120;
// Specify the image Fixed Width
logo.FixWidth = 110;
row1.Cells.Add();
// Add the image to paragraphs collection of the table cell
row1.Cells[0].Paragraphs.Add(logo);
// Create string variables with text containing html tags
string TitleString = "<font face=\"Arial\" size=6 color=\"#101090\"><b> Aspose.Pdf for .NET</b></font>";
string BodyString1 = "<font face=\"Arial\" size=2><br/>Aspose.Pdf for .NET is a non-graphical PDF� document reporting component that enables .NET applications to <b> create PDF documents from scratch </b> without utilizing Adobe Acrobat�. Aspose.Pdf for .NET is very affordably priced and offers a wealth of strong features including: compression, tables, graphs, images, hyperlinks, security and custom fonts. </font>";
// Create a text object to be added to the right of image
Aspose.Pdf.HtmlFragment TitleText = new Aspose.Pdf.HtmlFragment(TitleString + BodyString1);
row1.Cells.Add();
// Add the text paragraphs containing HTML text to the table cell
row1.Cells[1].Paragraphs.Add(TitleText);
// Set the vertical alignment of the row contents as Top
row1.Cells[1].VerticalAlignment = Aspose.Pdf.VerticalAlignment.Top;
// Create rows in the table and then cells in the rows
Aspose.Pdf.Row SecondRow = table1.Rows.Add();
SecondRow.Cells.Add();
// Set the row span value for Second row as 2
SecondRow.Cells[0].ColSpan = 2;
// Set the vertical alignment of the second row as Top
SecondRow.Cells[0].VerticalAlignment = Aspose.Pdf.VerticalAlignment.Top;
string SecondRowString = "<font face=\"Arial\" size=2>Aspose.Pdf for .NET supports the creation of PDF files through API and XML or XSL-FO templates. Aspose.Pdf for .NET is very easy to use and is provided with 14 fully featured demos written in both C# and Visual Basic.</font>";
Aspose.Pdf.HtmlFragment SecondRowText = new Aspose.Pdf.HtmlFragment(SecondRowString);
// Add the text paragraphs containing HTML text to the table cell
SecondRow.Cells[0].Paragraphs.Add(SecondRowText);
// Save the Pdf file
doc.Save(dataDir + "PlacingTextAroundImage_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Load source PDF file
Document doc = new Document(dataDir + "ExtractTextPage.pdf");
// Create TextFragment Absorber object with regular expression
TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("[TextFragmentAbsorber,companyname,Textbox,50]");
doc.Pages.Accept(textFragmentAbsorber);
// Replace each TextFragment
foreach (TextFragment textFragment in textFragmentAbsorber.TextFragments)
{
// Set font of text fragment being replaced
textFragment.TextState.Font = FontRepository.FindFont("Arial");
// Set font size
textFragment.TextState.FontSize = 12;
textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.Navy;
// Replace the text with larger string than placeholder
textFragment.Text = "This is a Larger String for the Testing of this issue";
}
dataDir = dataDir + "RearrangeContentsUsingTextReplacement_out.pdf";
// Save resultant PDF
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Open document
Document pdfDocument = new Document(dataDir + "RemoveAllText.pdf");
// Loop through all pages of PDF Document
for (int i = 1; i <= pdfDocument.Pages.Count; i++)
{
Page page = pdfDocument.Pages[i];
OperatorSelector operatorSelector = new OperatorSelector(new Aspose.Pdf.Operators.TextShowOperator());
// Select all text on the page
page.Contents.Accept(operatorSelector);
// Delete all text
page.Contents.Delete(operatorSelector.Selected);
}
// Save the document
pdfDocument.Save(dataDir + "RemoveAllText_out.pdf", Aspose.Pdf.SaveFormat.Pdf);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Open document
Document pdfDocument = new Document(dataDir + "RemoveAllText.pdf");
// Initiate TextFragmentAbsorber
TextFragmentAbsorber absorber = new TextFragmentAbsorber();
// Remove all absorbed text
absorber.RemoveAllText(pdfDocument);
// Save the document
pdfDocument.Save(dataDir + "RemoveAllText_out.pdf", Aspose.Pdf.SaveFormat.Pdf);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Load source PDF file
Document doc = new Document(dataDir + "ReplaceTextPage.pdf");
TextFragmentAbsorber absorber = new TextFragmentAbsorber(new TextEditOptions(TextEditOptions.FontReplace.RemoveUnusedFonts));
doc.Pages.Accept(absorber);
// Iterate through all the TextFragments
foreach (TextFragment textFragment in absorber.TextFragments)
{
textFragment.TextState.Font = FontRepository.FindFont("Arial, Bold");
}
dataDir = dataDir + "RemoveUnusedFonts_out.pdf";
// Save updated document
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
Aspose.Pdf.Document pdfApplicationDoc = new Aspose.Pdf.Document();
Aspose.Pdf.Page applicationFirstPage = (Aspose.Pdf.Page)pdfApplicationDoc.Pages.Add();
// Initialize new TextFragment with text containing required newline markers
Aspose.Pdf.Text.TextFragment textFragment = new Aspose.Pdf.Text.TextFragment("Applicant Name: " + Environment.NewLine + " Joe Smoe");
// Set text fragment properties if necessary
textFragment.TextState.FontSize = 12;
textFragment.TextState.Font = Aspose.Pdf.Text.FontRepository.FindFont("TimesNewRoman");
textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray;
textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.Red;
// Create TextParagraph object
TextParagraph par = new TextParagraph();
// Add new TextFragment to paragraph
par.AppendLine(textFragment);
// Set paragraph position
par.Position = new Aspose.Pdf.Text.Position(100, 600);
// Create TextBuilder object
TextBuilder textBuilder = new TextBuilder(applicationFirstPage);
// Add the TextParagraph using TextBuilder
textBuilder.AppendParagraph(par);
dataDir = dataDir + "RenderingReplaceableSymbols_out.pdf";
pdfApplicationDoc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
Document doc = new Document();
Page page = doc.Pages.Add();
MarginInfo marginInfo = new MarginInfo();
marginInfo.Top = 90;
marginInfo.Bottom = 50;
marginInfo.Left = 50;
marginInfo.Right = 50;
// Assign the marginInfo instance to Margin property of sec1.PageInfo
page.PageInfo.Margin = marginInfo;
HeaderFooter hfFirst = new HeaderFooter();
page.Header = hfFirst;
hfFirst.Margin.Left = 50;
hfFirst.Margin.Right = 50;
// Instantiate a Text paragraph that will store the content to show as header
TextFragment t1 = new TextFragment("report title");
t1.TextState.Font = FontRepository.FindFont("Arial");
t1.TextState.FontSize = 16;
t1.TextState.ForegroundColor = Aspose.Pdf.Color.Black;
t1.TextState.FontStyle = FontStyles.Bold;
t1.TextState.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Center;
t1.TextState.LineSpacing = 5f;
hfFirst.Paragraphs.Add(t1);
TextFragment t2 = new TextFragment("Report_Name");
t2.TextState.Font = FontRepository.FindFont("Arial");
t2.TextState.ForegroundColor = Aspose.Pdf.Color.Black;
t2.TextState.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Center;
t2.TextState.LineSpacing = 5f;
t2.TextState.FontSize = 12;
hfFirst.Paragraphs.Add(t2);
// Create a HeaderFooter object for the section
HeaderFooter hfFoot = new HeaderFooter();
// Set the HeaderFooter object to odd & even footer
page.Footer = hfFoot;
hfFoot.Margin.Left = 50;
hfFoot.Margin.Right = 50;
// Add a text paragraph containing current page number of total number of pages
TextFragment t3 = new TextFragment("Generated on test date");
TextFragment t4 = new TextFragment("report name ");
TextFragment t5 = new TextFragment("Page $p of $P");
// Instantiate a table object
Table tab2 = new Table();
// Add the table in paragraphs collection of the desired section
hfFoot.Paragraphs.Add(tab2);
// Set with column widths of the table
tab2.ColumnWidths = "165 172 165";
// Create rows in the table and then cells in the rows
Row row3 = tab2.Rows.Add();
row3.Cells.Add();
row3.Cells.Add();
row3.Cells.Add();
// Set the vertical allignment of the text as center alligned
row3.Cells[0].Alignment = Aspose.Pdf.HorizontalAlignment.Left;
row3.Cells[1].Alignment = Aspose.Pdf.HorizontalAlignment.Center;
row3.Cells[2].Alignment = Aspose.Pdf.HorizontalAlignment.Right;
row3.Cells[0].Paragraphs.Add(t3);
row3.Cells[1].Paragraphs.Add(t4);
row3.Cells[2].Paragraphs.Add(t5);
// Sec1.Paragraphs.Add(New Text("Aspose.Total for Java is a compilation of every Java component offered by Aspose. It is compiled on a#$NL" + "daily basis to ensure it contains the most up to date versions of each of our Java components. #$NL " + "Using Aspose.Total for Java developers can create a wide range of applications. #$NL #$NL #$NP" + "Aspose.Total for Java is a compilation of every Java component offered by Aspose. It is compiled on a#$NL" + "daily basis to ensure it contains the most up to date versions of each of our Java components. #$NL " + "Using Aspose.Total for Java developers can create a wide range of applications. #$NL #$NL #$NP" + "Aspose.Total for Java is a compilation of every Java component offered by Aspose. It is compiled on a#$NL" + "daily basis to ensure it contains the most up to date versions of each of our Java components. #$NL " + "Using Aspose.Total for Java developers can create a wide range of applications. #$NL #$NL"))
Table table = new Table();
table.ColumnWidths = "33% 33% 34%";
table.DefaultCellPadding = new MarginInfo();
table.DefaultCellPadding.Top = 10;
table.DefaultCellPadding.Bottom = 10;
// Add the table in paragraphs collection of the desired section
page.Paragraphs.Add(table);
// Set default cell border using BorderInfo object
table.DefaultCellBorder = new BorderInfo(BorderSide.All, 0.1f);
// Set table border using another customized BorderInfo object
table.Border = new BorderInfo(BorderSide.All, 1f);
table.RepeatingRowsCount = 1;
// Create rows in the table and then cells in the rows
Row row1 = table.Rows.Add();
row1.Cells.Add("col1");
row1.Cells.Add("col2");
row1.Cells.Add("col3");
const string CRLF = "\r\n";
for (int i = 0; i <= 10; i++)
{
Row row = table.Rows.Add();
row.IsRowBroken = true;
for (int c = 0; c <= 2; c++)
{
Cell c1;
if (c == 2)
c1 = row.Cells.Add("Aspose.Total for Java is a compilation of every Java component offered by Aspose. It is compiled on a" + CRLF + "daily basis to ensure it contains the most up to date versions of each of our Java components. " + CRLF + "daily basis to ensure it contains the most up to date versions of each of our Java components. " + CRLF + "Using Aspose.Total for Java developers can create a wide range of applications.");
else
c1 = row.Cells.Add("item1" + c);
c1.Margin = new MarginInfo();
c1.Margin.Left = 30;
c1.Margin.Top = 10;
c1.Margin.Bottom = 10;
}
}
dataDir = dataDir + "ReplaceableSymbolsInHeaderFooter_out.pdf";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Open document
Document pdfDocument = new Document(dataDir + "ReplaceTextPage.pdf");
// Create TextAbsorber object to find all instances of the input search phrase
TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("text");
// Accept the absorber for all the pages
pdfDocument.Pages.Accept(textFragmentAbsorber);
// Get the extracted text fragments
TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;
if (textFragmentCollection.Count > 0)
{
// Get first occurance of text and replace
TextFragment textFragment = textFragmentCollection[1];
// Update text and other properties
textFragment.Text = "New Phrase";
textFragment.TextState.Font = FontRepository.FindFont("Verdana");
textFragment.TextState.FontSize = 22;
textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Blue);
dataDir = dataDir + "ReplaceFirstOccurrence_out.pdf";
pdfDocument.Save(dataDir);
Console.WriteLine("\nText replaced successfully.\nFile saved at " + dataDir);
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Load source PDF file
Document pdfDocument = new Document(dataDir + "ReplaceTextPage.pdf");
// Search text fragments and set edit option as remove unused fonts
TextFragmentAbsorber absorber = new TextFragmentAbsorber(new TextEditOptions(TextEditOptions.FontReplace.RemoveUnusedFonts));
// Accept the absorber for all the pages
pdfDocument.Pages.Accept(absorber);
// Traverse through all the TextFragments
foreach (TextFragment textFragment in absorber.TextFragments)
{
// If the font name is ArialMT, replace font name with Arial
if (textFragment.TextState.Font.FontName == "Arial,Bold")
{
textFragment.TextState.Font = FontRepository.FindFont("Arial");
}
}
dataDir = dataDir + "ReplaceFonts_out.pdf";
// Save updated document
pdfDocument.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Open document
Document pdfDocument = new Document(dataDir + "ReplaceTextAll.pdf");
// Create TextAbsorber object to find all instances of the input search phrase
TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("text");
// Accept the absorber for all the pages
pdfDocument.Pages.Accept(textFragmentAbsorber);
// Get the extracted text fragments
TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;
// Loop through the fragments
foreach (TextFragment textFragment in textFragmentCollection)
{
// Update text and other properties
textFragment.Text = "TEXT";
textFragment.TextState.Font = FontRepository.FindFont("Verdana");
textFragment.TextState.FontSize = 22;
textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Blue);
textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Green);
}
dataDir = dataDir + "ReplaceTextAll_out.pdf";
// Save resulting PDF document.
pdfDocument.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Open document
Document pdfDocument = new Document(dataDir + "SearchRegularExpressionPage.pdf");
// Create TextAbsorber object to find all the phrases matching the regular expression
TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("\\d{4}-\\d{4}"); // Like 1999-2000
// Set text search option to specify regular expression usage
TextSearchOptions textSearchOptions = new TextSearchOptions(true);
textFragmentAbsorber.TextSearchOptions = textSearchOptions;
// Accept the absorber for a single page
pdfDocument.Pages[1].Accept(textFragmentAbsorber);
// Get the extracted text fragments
TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;
// Loop through the fragments
foreach (TextFragment textFragment in textFragmentCollection)
{
// Update text and other properties
textFragment.Text = "New Phrase";
// Set to an instance of an object.
textFragment.TextState.Font = FontRepository.FindFont("Verdana");
textFragment.TextState.FontSize = 22;
textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Blue);
textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Green);
}
dataDir = dataDir + "ReplaceTextonRegularExpression_out.pdf";
pdfDocument.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// Accept the absorber for a particular page
pdfDocument.Pages[2].Accept(textFragmentAbsorber);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Initialize document object
Document pdfDocument = new Document();
// Get particular page
Page pdfPage = (Page)pdfDocument.Pages.Add();
TextParagraph paragraph = new TextParagraph();
paragraph.Position = new Position(200, 600);
// Create text fragment
TextFragment textFragment1 = new TextFragment("rotated text");
// Set text properties
textFragment1.TextState.FontSize = 12;
textFragment1.TextState.Font = FontRepository.FindFont("TimesNewRoman");
// Set rotation
textFragment1.TextState.Rotation = 45;
// Create text fragment
TextFragment textFragment2 = new TextFragment("main text");
// Set text properties
textFragment2.TextState.FontSize = 12;
textFragment2.TextState.Font = FontRepository.FindFont("TimesNewRoman");
// Create text fragment
TextFragment textFragment3 = new TextFragment("another rotated text");
// Set text properties
textFragment3.TextState.FontSize = 12;
textFragment3.TextState.Font = FontRepository.FindFont("TimesNewRoman");
// Set rotation
textFragment3.TextState.Rotation = -45;
// Append the text fragments to the paragraph
paragraph.AppendLine(textFragment1);
paragraph.AppendLine(textFragment2);
paragraph.AppendLine(textFragment3);
// Create TextBuilder object
TextBuilder textBuilder = new TextBuilder(pdfPage);
// Append the text paragraph to the PDF page
textBuilder.AppendParagraph(paragraph);
// Save document
pdfDocument.Save(dataDir + "TextFragmentTests_Rotated2_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Initialize document object
Document pdfDocument = new Document();
// Get particular page
Page pdfPage = (Page)pdfDocument.Pages.Add();
// Create text fragment
TextFragment textFragment1 = new TextFragment("main text");
textFragment1.Position = new Position(100, 600);
// Set text properties
textFragment1.TextState.FontSize = 12;
textFragment1.TextState.Font = FontRepository.FindFont("TimesNewRoman");
// Create rotated text fragment
TextFragment textFragment2 = new TextFragment("rotated text");
textFragment2.Position = new Position(200, 600);
// Set text properties
textFragment2.TextState.FontSize = 12;
textFragment2.TextState.Font = FontRepository.FindFont("TimesNewRoman");
textFragment2.TextState.Rotation = 45;
// Create rotated text fragment
TextFragment textFragment3 = new TextFragment("rotated text");
textFragment3.Position = new Position(300, 600);
// Set text properties
textFragment3.TextState.FontSize = 12;
textFragment3.TextState.Font = FontRepository.FindFont("TimesNewRoman");
textFragment3.TextState.Rotation = 90;
// create TextBuilder object
TextBuilder textBuilder = new TextBuilder(pdfPage);
// Append the text fragment to the PDF page
textBuilder.AppendText(textFragment1);
textBuilder.AppendText(textFragment2);
textBuilder.AppendText(textFragment3);
// Save document
pdfDocument.Save(dataDir + "TextFragmentTests_Rotated1_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Initialize document object
Document pdfDocument = new Document();
// Get particular page
Page pdfPage = (Page)pdfDocument.Pages.Add();
// Create text fragment
TextFragment textFragment1 = new TextFragment("main text");
// Set text properties
textFragment1.TextState.FontSize = 12;
textFragment1.TextState.Font = FontRepository.FindFont("TimesNewRoman");
// Create text fragment
TextFragment textFragment2 = new TextFragment("rotated text");
// Set text properties
textFragment2.TextState.FontSize = 12;
textFragment2.TextState.Font = FontRepository.FindFont("TimesNewRoman");
// Set rotation
textFragment2.TextState.Rotation = 315;
// Create text fragment
TextFragment textFragment3 = new TextFragment("rotated text");
// Set text properties
textFragment3.TextState.FontSize = 12;
textFragment3.TextState.Font = FontRepository.FindFont("TimesNewRoman");
// Set rotation
textFragment3.TextState.Rotation = 270;
pdfPage.Paragraphs.Add(textFragment1);
pdfPage.Paragraphs.Add(textFragment2);
pdfPage.Paragraphs.Add(textFragment3);
// Save document
pdfDocument.Save(dataDir + "TextFragmentTests_Rotated3_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Initialize document object
Document pdfDocument = new Document();
// Get particular page
Page pdfPage = (Page)pdfDocument.Pages.Add();
for (int i = 0; i < 4; i++)
{
TextParagraph paragraph = new TextParagraph();
paragraph.Position = new Position(200, 600);
// Specify rotation
paragraph.Rotation = i * 90 + 45;
// Create text fragment
TextFragment textFragment1 = new TextFragment("Paragraph Text");
// Create text fragment
textFragment1.TextState.FontSize = 12;
textFragment1.TextState.Font = FontRepository.FindFont("TimesNewRoman");
textFragment1.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray;
textFragment1.TextState.ForegroundColor = Aspose.Pdf.Color.Blue;
// Create text fragment
TextFragment textFragment2 = new TextFragment("Second line of text");
// Set text properties
textFragment2.TextState.FontSize = 12;
textFragment2.TextState.Font = FontRepository.FindFont("TimesNewRoman");
textFragment2.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray;
textFragment2.TextState.ForegroundColor = Aspose.Pdf.Color.Blue;
// Create text fragment
TextFragment textFragment3 = new TextFragment("And some more text...");
// Set text properties
textFragment3.TextState.FontSize = 12;
textFragment3.TextState.Font = FontRepository.FindFont("TimesNewRoman");
textFragment3.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray;
textFragment3.TextState.ForegroundColor = Aspose.Pdf.Color.Blue;
textFragment3.TextState.Underline = true;
paragraph.AppendLine(textFragment1);
paragraph.AppendLine(textFragment2);
paragraph.AppendLine(textFragment3);
// Create TextBuilder object
TextBuilder textBuilder = new TextBuilder(pdfPage);
// Append the text fragment to the PDF page
textBuilder.AppendParagraph(paragraph);
}
// Save document
pdfDocument.Save(dataDir + "TextFragmentTests_Rotated4_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Open document
Document pdfDocument = new Document(dataDir + "SearchAndGetTextFromAll.pdf");
// Create TextAbsorber object to find all instances of the input search phrase
TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("text");
// Accept the absorber for all the pages
pdfDocument.Pages.Accept(textFragmentAbsorber);
// Get the extracted text fragments
TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;
// Loop through the fragments
foreach (TextFragment textFragment in textFragmentCollection)
{
Console.WriteLine("Text : {0} ", textFragment.Text);
Console.WriteLine("Position : {0} ", textFragment.Position);
Console.WriteLine("XIndent : {0} ", textFragment.Position.XIndent);
Console.WriteLine("YIndent : {0} ", textFragment.Position.YIndent);
Console.WriteLine("Font - Name : {0}", textFragment.TextState.Font.FontName);
Console.WriteLine("Font - IsAccessible : {0} ", textFragment.TextState.Font.IsAccessible);
Console.WriteLine("Font - IsEmbedded : {0} ", textFragment.TextState.Font.IsEmbedded);
Console.WriteLine("Font - IsSubset : {0} ", textFragment.TextState.Font.IsSubset);
Console.WriteLine("Font Size : {0} ", textFragment.TextState.FontSize);
Console.WriteLine("Foreground Color : {0} ", textFragment.TextState.ForegroundColor);
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Open document
Document pdfDocument = new Document(dataDir + "SearchAndGetTextPage.pdf");
// Create TextAbsorber object to find all instances of the input search phrase
TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("Figure");
// Accept the absorber for all the pages
pdfDocument.Pages.Accept(textFragmentAbsorber);
// Get the extracted text fragments
TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;
// Loop through the fragments
foreach (TextFragment textFragment in textFragmentCollection)
{
foreach (TextSegment textSegment in textFragment.Segments)
{
Console.WriteLine("Text : {0} ", textSegment.Text);
Console.WriteLine("Position : {0} ", textSegment.Position);
Console.WriteLine("XIndent : {0} ", textSegment.Position.XIndent);
Console.WriteLine("YIndent : {0} ", textSegment.Position.YIndent);
Console.WriteLine("Font - Name : {0}", textSegment.TextState.Font.FontName);
Console.WriteLine("Font - IsAccessible : {0} ", textSegment.TextState.Font.IsAccessible);
Console.WriteLine("Font - IsEmbedded : {0} ", textSegment.TextState.Font.IsEmbedded);
Console.WriteLine("Font - IsSubset : {0} ", textSegment.TextState.Font.IsSubset);
Console.WriteLine("Font Size : {0} ", textSegment.TextState.FontSize);
Console.WriteLine("Foreground Color : {0} ", textSegment.TextState.ForegroundColor);
}
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Open document
Document pdfDocument = new Document(dataDir + "SearchRegularExpressionAll.pdf");
// Create TextAbsorber object to find all the phrases matching the regular expression
TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("\\d{4}-\\d{4}"); // Like 1999-2000
// Set text search option to specify regular expression usage
TextSearchOptions textSearchOptions = new TextSearchOptions(true);
textFragmentAbsorber.TextSearchOptions = textSearchOptions;
// Accept the absorber for all the pages
pdfDocument.Pages.Accept(textFragmentAbsorber);
// Get the extracted text fragments
TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;
// Loop through the fragments
foreach (TextFragment textFragment in textFragmentCollection)
{
Console.WriteLine("Text : {0} ", textFragment.Text);
Console.WriteLine("Position : {0} ", textFragment.Position);
Console.WriteLine("XIndent : {0} ", textFragment.Position.XIndent);
Console.WriteLine("YIndent : {0} ", textFragment.Position.YIndent);
Console.WriteLine("Font - Name : {0}", textFragment.TextState.Font.FontName);
Console.WriteLine("Font - IsAccessible : {0} ", textFragment.TextState.Font.IsAccessible);
Console.WriteLine("Font - IsEmbedded : {0} ", textFragment.TextState.Font.IsEmbedded);
Console.WriteLine("Font - IsSubset : {0} ", textFragment.TextState.Font.IsSubset);
Console.WriteLine("Font Size : {0} ", textFragment.TextState.FontSize);
Console.WriteLine("Foreground Color : {0} ", textFragment.TextState.ForegroundColor);
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void DrawBox(PdfContentEditor editor, int page, TextSegment segment, System.Drawing.Color color)
{
var lineInfo = new LineInfo();
lineInfo.VerticeCoordinate = new[] {
(float)segment.Rectangle.LLX, (float)segment.Rectangle.LLY,
(float)segment.Rectangle.LLX, (float)segment.Rectangle.URY,
(float)segment.Rectangle.URX, (float)segment.Rectangle.URY,
(float)segment.Rectangle.URX, (float)segment.Rectangle.LLY
};
lineInfo.Visibility = true;
lineInfo.LineColor = color;
editor.CreatePolygon(lineInfo, page, new System.Drawing.Rectangle(0, 0, 0, 0), null);
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Open document
Document document = new Document(dataDir + "SearchAndGetTextFromAll.pdf");
// Create TextAbsorber object to find all the phrases matching the regular expression
TextFragmentAbsorber textAbsorber = new TextFragmentAbsorber(@"[\S]+");
TextSearchOptions textSearchOptions = new TextSearchOptions(true);
textAbsorber.TextSearchOptions = textSearchOptions;
document.Pages.Accept(textAbsorber);
var editor = new PdfContentEditor(document);
foreach (TextFragment textFragment in textAbsorber.TextFragments)
{
foreach (TextSegment textSegment in textFragment.Segments)
{
DrawBox(editor, textFragment.Page.Number, textSegment, System.Drawing.Color.Red);
}
}
dataDir = dataDir + "SearchTextAndDrawRectangle_out.pdf";
document.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// Accept the absorber for all the pages
pdfDocument.Pages[2].Accept(textFragmentAbsorber);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Create Regex object to find all words
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"[\S]+");
// Open document
Aspose.Pdf.Document document = new Aspose.Pdf.Document(dataDir + "SearchTextRegex.pdf");
// Get a particular page
Page page = document.Pages[1];
// Create TextAbsorber object to find all instances of the input regex
TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(regex);
textFragmentAbsorber.TextSearchOptions.IsRegularExpressionUsed = true;
// Accept the absorber for the page
page.Accept(textFragmentAbsorber);
// Get the extracted text fragments
TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;
// Loop through the fragments
foreach (TextFragment textFragment in textFragmentCollection)
{
Console.WriteLine(textFragment.Text);
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
HtmlFragment html = new HtmlFragment("some text");
html.TextState = new TextState();
html.TextState.Font = FontRepository.FindFont("Calibri");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Create Document instance
Document pdfDocument = new Document();
// Add page to pages collection of Document
Page page = pdfDocument.Pages.Add();
// Create TextBuilder instance
TextBuilder builder = new TextBuilder(pdfDocument.Pages[1]);
// Create text fragment instance with sample contents
TextFragment wideFragment = new TextFragment("Text with increased character spacing");
wideFragment.TextState.ApplyChangesFrom(new TextState("Arial", 12));
// Specify character spacing for TextFragment
wideFragment.TextState.CharacterSpacing = 2.0f;
// Specify the position of TextFragment
wideFragment.Position = new Position(100, 650);
// Append TextFragment to TextBuilder instance
builder.AppendText(wideFragment);
dataDir = dataDir + "CharacterSpacingUsingTextBuilderAndFragment_out.pdf";
// Save resulting PDF document.
pdfDocument.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Create Document instance
Document pdfDocument = new Document();
// Add page to pages collection of Document
Page page = pdfDocument.Pages.Add();
// Create TextBuilder instance
TextBuilder builder = new TextBuilder(pdfDocument.Pages[1]);
// Instantiate TextParagraph instance
TextParagraph paragraph = new TextParagraph();
// Create TextState instance to specify font name and size
TextState state = new TextState("Arial", 12);
// Specify the character spacing
state.CharacterSpacing = 1.5f;
// Append text to TextParagraph object
paragraph.AppendLine("This is paragraph with character spacing", state);
// Specify the position for TextParagraph
paragraph.Position = new Position(100, 550);
// Append TextParagraph to TextBuilder instance
builder.AppendParagraph(paragraph);
dataDir = dataDir + "CharacterSpacingUsingTextBuilderAndParagraph_out.pdf";
// Save resulting PDF document.
pdfDocument.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Create Document instance
Document pdfDocument = new Document();
// Add page to pages collection of Document
Page page = pdfDocument.Pages.Add();
// Instantiate TextStamp instance with sample text
TextStamp stamp = new TextStamp("This is text stamp with character spacing");
// Specify font name for Stamp object
stamp.TextState.Font = FontRepository.FindFont("Arial");
// Specify Font size for TextStamp
stamp.TextState.FontSize = 12;
// Specify character specing as 1f
stamp.TextState.CharacterSpacing = 1f;
// Set the XIndent for Stamp
stamp.XIndent = 100;
// Set the YIndent for Stamp
stamp.YIndent = 500;
// Add textual stamp to page instance
stamp.Put(page);
dataDir = dataDir + "CharacterSpacingUsingTextStamp_out.pdf";
// Save resulting PDF document.
pdfDocument.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
string fontFile = dataDir + "HPSimplified.TTF";
// Load input PDF file
Document doc = new Document();
//Create TextFormattingOptions with LineSpacingMode.FullSize
TextFormattingOptions formattingOptions = new TextFormattingOptions();
formattingOptions.LineSpacing = TextFormattingOptions.LineSpacingMode.FullSize;
// Create text builder object for first page of document
//TextBuilder textBuilder = new TextBuilder(doc.Pages[1]);
// Create text fragment with sample string
TextFragment textFragment = new TextFragment("Hello world");
if (fontFile != "")
{
// Load the TrueType font into stream object
using (FileStream fontStream = System.IO.File.OpenRead(fontFile))
{
// Set the font name for text string
textFragment.TextState.Font = FontRepository.OpenFont(fontStream, FontTypes.TTF);
// Specify the position for Text Fragment
textFragment.Position = new Position(100, 600);
//Set TextFormattingOptions of current fragment to predefined(which points to LineSpacingMode.FullSize)
textFragment.TextState.FormattingOptions = formattingOptions;
// Add the text to TextBuilder so that it can be placed over the PDF file
//textBuilder.AppendText(textFragment);
var page = doc.Pages.Add();
page.Paragraphs.Add(textFragment);
}
dataDir = dataDir + "SpecifyLineSpacing_out.pdf";
// Save resulting PDF document
doc.Save(dataDir);
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
Aspose.Pdf.Document doc = new Document();
doc.Pages.Add();
Aspose.Pdf.FloatingBox floatBox = new Aspose.Pdf.FloatingBox(100, 100);
floatBox.VerticalAlignment = VerticalAlignment.Bottom;
floatBox.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Right;
floatBox.Paragraphs.Add(new TextFragment("FloatingBox_bottom"));
floatBox.Border = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, Aspose.Pdf.Color.Blue);
doc.Pages[1].Paragraphs.Add(floatBox);
Aspose.Pdf.FloatingBox floatBox1 = new Aspose.Pdf.FloatingBox(100, 100);
floatBox1.VerticalAlignment = VerticalAlignment.Center;
floatBox1.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Right;
floatBox1.Paragraphs.Add(new TextFragment("FloatingBox_center"));
floatBox1.Border = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, Aspose.Pdf.Color.Blue);
doc.Pages[1].Paragraphs.Add(floatBox1);
Aspose.Pdf.FloatingBox floatBox2 = new Aspose.Pdf.FloatingBox(100, 100);
floatBox2.VerticalAlignment = VerticalAlignment.Top;
floatBox2.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Right;
floatBox2.Paragraphs.Add(new TextFragment("FloatingBox_top"));
floatBox2.Border = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, Aspose.Pdf.Color.Blue);
doc.Pages[1].Paragraphs.Add(floatBox2);
doc.Save(dataDir + "FloatingBox_alignment_review_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Instantiate Document instance
Document doc = new Document();
// Add page to pages collection of Document instance
Page page = doc.Pages.Add();
// Create TextFragmnet
TextFragment text = new TextFragment("Hello World.. ");
// Add text fragment to paragraphs collection of Page object
page.Paragraphs.Add(text);
// Create an image instance
Aspose.Pdf.Image image = new Aspose.Pdf.Image();
// Set image as inline paragraph so that it appears right after
// The previous paragraph object (TextFragment)
image.IsInLineParagraph = true;
// Specify image file path
image.File = dataDir + "aspose-logo.jpg";
// Set image Height (optional)
image.FixHeight = 30;
// Set Image Width (optional)
image.FixWidth = 100;
// Add image to paragraphs collection of page object
page.Paragraphs.Add(image);
// Re-initialize TextFragment object with different contents
text = new TextFragment(" Hello Again..");
// Set TextFragment as inline paragraph
text.IsInLineParagraph = true;
// Add newly created TextFragment to paragraphs collection of page
page.Paragraphs.Add(text);
dataDir = dataDir + "TextAndImageAsParagraph_out.pdf";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
TextFragmentAbsorber textFragmentAbsorber;
// In order to search exact match of a word, you may consider using regular expression.
textFragmentAbsorber = new TextFragmentAbsorber(@"\bWord\b", new TextSearchOptions(true));
// In order to search a string in either upper case or lowercase, you may consider using regular expression.
textFragmentAbsorber = new TextFragmentAbsorber("(?i)Line", new TextSearchOptions(true));
// In order to search all the strings (parse all strings) inside PDF document, please try using following regular expression.
textFragmentAbsorber = new TextFragmentAbsorber(@"[\S]+");
// Find match of search string and get anything after the string till line break.
textFragmentAbsorber = new TextFragmentAbsorber(@"(?i)the ((.)*)");
// Please use following regular expression to find text following to the regex match.
textFragmentAbsorber = new TextFragmentAbsorber(@"(?<=word).*");
// In order to search Hyperlink/URL's inside PDF document, please try using following regular expression.
textFragmentAbsorber = new TextFragmentAbsorber(@"(http|ftp|https):\/\/([\w\-_]+(?:(?:\.[\w\-_]+)+))([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_Text();
// Create a new Document Object
Document doc = new Document();
// Add Page in Pages Collection
Page page = doc.Pages.Add();
// Create a Table
Table table = new Table();
// Add a row into Table
Row row = table.Rows.Add();
// Add Cell with Latex Script to add methematical expressions/formulae
string latexText2 = @"\documentclass{article}
\begin{document}
Latex and the document class will normally take care of page layout issues for you. For submission to an academic publication, this entire topic will be out
\end{document}";
Cell cell = row.Cells.Add();
cell.Margin = new MarginInfo { Left = 20, Right = 20, Top = 20, Bottom = 20 };
HtmlFragment text2 = new HtmlFragment(latexText2);
cell.Paragraphs.Add(text2);
// Add table inside page
page.Paragraphs.Add(table);
// Save the document
doc.Save(dataDir + "LatextScriptInPdf2_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
var dataDir = RunExamples.GetDataDir_AsposePdf_Text();
var s = @"
\usepackage{amsmath,amsthm}
\begin{document}
\begin{proof} The proof is a follows:
\begin{align}
(x+y)^3&=(x+y)(x+y)^2
(x+y)(x^2+2xy+y^2)\\
&=x^3+3x^2y+3xy^3+x^3.\qedhere
\end{align}
\end{proof}
\end{document}";
var doc = new Document();
var page = doc.Pages.Add();
var latex = new LatexFragment(s);
page.Paragraphs.Add(latex);
doc.Save(dataDir + "Script_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Open Pdf Document
Document document = new Document(dataDir + "StructureElementsTree.pdf");
// Get Content for work with TaggedPdf
ITaggedContent taggedContent = document.TaggedContent;
// Access to root element(s)
ElementList elementList = taggedContent.StructTreeRootElement.ChildElements;
foreach (Element element in elementList)
{
if (element is StructureElement)
{
StructureElement structureElement = element as StructureElement;
// Get properties
string title = structureElement.Title;
string language = structureElement.Language;
string actualText = structureElement.ActualText;
string expansionText = structureElement.ExpansionText;
string alternativeText = structureElement.AlternativeText;
}
}
// Access to children elements of first element in root element
elementList = taggedContent.RootElement.ChildElements[1].ChildElements;
foreach (Element element in elementList)
{
if (element is StructureElement)
{
StructureElement structureElement = element as StructureElement;
// Set properties
structureElement.Title = "title";
structureElement.Language = "fr-FR";
structureElement.ActualText = "actual text";
structureElement.ExpansionText = "exp";
structureElement.AlternativeText = "alt";
}
}
// Save Tagged Pdf Document
document.Save(dataDir + "AccessChildrenElements.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
Document doc = new Document();
Page page = doc.Pages.Add();
Layer layer = new Layer("oc1", "Red Line");
layer.Contents.Add(new Aspose.Pdf.Operators.SetRGBColorStroke(1, 0, 0));
layer.Contents.Add(new Aspose.Pdf.Operators.MoveTo(500, 700));
layer.Contents.Add(new Aspose.Pdf.Operators.LineTo(400, 700));
layer.Contents.Add(new Aspose.Pdf.Operators.Stroke());
page.Layers = new List<Layer>();
page.Layers.Add(layer);
layer = new Layer("oc2", "Green Line");
layer.Contents.Add(new Aspose.Pdf.Operators.SetRGBColorStroke(0, 1, 0));
layer.Contents.Add(new Aspose.Pdf.Operators.MoveTo(500, 750));
layer.Contents.Add(new Aspose.Pdf.Operators.LineTo(400, 750));
layer.Contents.Add(new Aspose.Pdf.Operators.Stroke());
page.Layers.Add(layer);
layer = new Layer("oc3", "Blue Line");
layer.Contents.Add(new Aspose.Pdf.Operators.SetRGBColorStroke(0, 0, 1));
layer.Contents.Add(new Aspose.Pdf.Operators.MoveTo(500, 800));
layer.Contents.Add(new Aspose.Pdf.Operators.LineTo(400, 800));
layer.Contents.Add(new Aspose.Pdf.Operators.Stroke());
page.Layers.Add(layer);
dataDir = dataDir + "AddLayers_out.pdf";
doc.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Open document
Document pdfDocument = new Document(dataDir + "OptimizeDocument.pdf");
// Set AllowReusePageContent option
var optimizeOptions = new Pdf.Optimization.OptimizationOptions
{
AllowReusePageContent = true
};
Console.WriteLine("Start");
// Optimize PDF document using OptimizationOptions
pdfDocument.OptimizeResources(optimizeOptions);
// Save updated document
pdfDocument.Save(dataDir + "OptimizeDocument_out.pdf");
Console.WriteLine("Finished");
var fi1 = new System.IO.FileInfo(dataDir + "OptimizeDocument.pdf");
var fi2 = new System.IO.FileInfo(dataDir + "OptimizeDocument_out.pdf");
Console.WriteLine("Original file size: {0}. Reduced file size: {1}", fi1.Length, fi2.Length);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
Document document = new Document();
ITaggedContent taggedContent = document.TaggedContent;
taggedContent.SetTitle("CreatePDFwithTaggedImage");
taggedContent.SetLanguage("en-US");
IllustrationElement figure1 = taggedContent.CreateFigureElement();
taggedContent.RootElement.AppendChild(figure1);
figure1.AlternativeText = "Aspose Logo";
figure1.Title = "Image 1";
figure1.SetTag("Fig");
// Add image with resolution 300 DPI (by default)
figure1.SetImage(dataDir + @"aspose-logo.jpg");
// Save PDF Document
document.Save(dataDir + "PDFwithTaggedImage.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Create Pdf Document
Document document = new Document();
// Get Content for work with TaggedPdf
ITaggedContent taggedContent = document.TaggedContent;
// Set Title and Language for Documnet
taggedContent.SetTitle("Tagged Pdf Document");
taggedContent.SetLanguage("en-US");
// Create Text Block-Level Structure Elements
HeaderElement headerElement = taggedContent.CreateHeaderElement();
headerElement.ActualText = "Heading 1";
ParagraphElement paragraphElement1 = taggedContent.CreateParagraphElement();
paragraphElement1.ActualText = "test1";
ParagraphElement paragraphElement2 = taggedContent.CreateParagraphElement();
paragraphElement2.ActualText = "test 2";
ParagraphElement paragraphElement3 = taggedContent.CreateParagraphElement();
paragraphElement3.ActualText = "test 3";
ParagraphElement paragraphElement4 = taggedContent.CreateParagraphElement();
paragraphElement4.ActualText = "test 4";
ParagraphElement paragraphElement5 = taggedContent.CreateParagraphElement();
paragraphElement5.ActualText = "test 5";
ParagraphElement paragraphElement6 = taggedContent.CreateParagraphElement();
paragraphElement6.ActualText = "test 6";
ParagraphElement paragraphElement7 = taggedContent.CreateParagraphElement();
paragraphElement7.ActualText = "test 7";
// Save PDF Document
document.Save( dataDir + "PDFwithTaggedText.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Create Pdf Document
Document document = new Document();
// Get Content for work with TaggedPdf
ITaggedContent taggedContent = document.TaggedContent;
// Set Title and Language for Documnet
taggedContent.SetTitle("Tagged Pdf Document");
taggedContent.SetLanguage("en-US");
// Create Grouping Elements
PartElement partElement = taggedContent.CreatePartElement();
ArtElement artElement = taggedContent.CreateArtElement();
SectElement sectElement = taggedContent.CreateSectElement();
DivElement divElement = taggedContent.CreateDivElement();
BlockQuoteElement blockQuoteElement = taggedContent.CreateBlockQuoteElement();
CaptionElement captionElement = taggedContent.CreateCaptionElement();
TOCElement tocElement = taggedContent.CreateTOCElement();
TOCIElement tociElement = taggedContent.CreateTOCIElement();
IndexElement indexElement = taggedContent.CreateIndexElement();
NonStructElement nonStructElement = taggedContent.CreateNonStructElement();
PrivateElement privateElement = taggedContent.CreatePrivateElement();
// Create Text Block-Level Structure Elements
ParagraphElement paragraphElement = taggedContent.CreateParagraphElement();
HeaderElement headerElement = taggedContent.CreateHeaderElement();
HeaderElement h1Element = taggedContent.CreateHeaderElement(1);
// Create Text Inline-Level Structure Elements
SpanElement spanElement = taggedContent.CreateSpanElement();
QuoteElement quoteElement = taggedContent.CreateQuoteElement();
NoteElement noteElement = taggedContent.CreateNoteElement();
// Create Illustration Structure Elements
FigureElement figureElement = taggedContent.CreateFigureElement();
FormulaElement formulaElement = taggedContent.CreateFormulaElement();
// Methods are under development
ListElement listElement = taggedContent.CreateListElement();
TableElement tableElement = taggedContent.CreateTableElement();
ReferenceElement referenceElement = taggedContent.CreateReferenceElement();
BibEntryElement bibEntryElement = taggedContent.CreateBibEntryElement();
CodeElement codeElement = taggedContent.CreateCodeElement();
LinkElement linkElement = taggedContent.CreateLinkElement();
AnnotElement annotElement = taggedContent.CreateAnnotElement();
RubyElement rubyElement = taggedContent.CreateRubyElement();
WarichuElement warichuElement = taggedContent.CreateWarichuElement();
FormElement formElement = taggedContent.CreateFormElement();
// Save Tagged Pdf Document
document.Save(dataDir + "StructureElements.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Create Pdf Document
Document document = new Document();
// Get Content for work with TaggedPdf
ITaggedContent taggedContent = document.TaggedContent;
// Set Title and Language for Documnet
taggedContent.SetTitle("Tagged Pdf Document");
taggedContent.SetLanguage("en-US");
// Get root structure element (Document)
StructureElement rootElement = taggedContent.RootElement;
// Create Logical Structure
SectElement sect1 = taggedContent.CreateSectElement();
rootElement.AppendChild(sect1);
SectElement sect2 = taggedContent.CreateSectElement();
rootElement.AppendChild(sect2);
DivElement div11 = taggedContent.CreateDivElement();
sect1.AppendChild(div11);
DivElement div12 = taggedContent.CreateDivElement();
sect1.AppendChild(div12);
ArtElement art21 = taggedContent.CreateArtElement();
sect2.AppendChild(art21);
ArtElement art22 = taggedContent.CreateArtElement();
sect2.AppendChild(art22);
DivElement div211 = taggedContent.CreateDivElement();
art21.AppendChild(div211);
DivElement div212 = taggedContent.CreateDivElement();
art21.AppendChild(div212);
DivElement div221 = taggedContent.CreateDivElement();
art22.AppendChild(div221);
DivElement div222 = taggedContent.CreateDivElement();
art22.AppendChild(div222);
SectElement sect3 = taggedContent.CreateSectElement();
rootElement.AppendChild(sect3);
DivElement div31 = taggedContent.CreateDivElement();
sect3.AppendChild(div31);
// Save Tagged Pdf Document
document.Save(dataDir + "StructureElementsTree.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
string inFile = RunExamples.GetDataDir_AsposePdf_WorkingDocuments() + "42824.pdf";
string outFile = RunExamples.GetDataDir_AsposePdf_WorkingDocuments() + "42824_out.pdf";
// Load an existing PDF files
Document doc = new Document(inFile);
// Get access to first page of PDF file
Aspose.Pdf.Page tocPage = doc.Pages.Insert(1);
// Create object to represent TOC information
TocInfo tocInfo = new TocInfo();
TextFragment title = new TextFragment("Table Of Contents");
title.TextState.FontSize = 20;
title.TextState.FontStyle = FontStyles.Bold;
// Set the title for TOC
tocInfo.Title = title;
tocInfo.PageNumbersPrefix = "P";
tocPage.TocInfo = tocInfo;
for (int i = 1; i<doc.Pages.Count; i++)
{
// Create Heading object
Aspose.Pdf.Heading heading2 = new Aspose.Pdf.Heading(1);
TextSegment segment2 = new TextSegment();
heading2.TocPage = tocPage;
heading2.Segments.Add(segment2);
// Specify the destination page for heading object
heading2.DestinationPage = doc.Pages[i + 1];
// Destination page
heading2.Top = doc.Pages[i + 1].Rect.Height;
// Destination coordinate
segment2.Text = "Page " + i.ToString();
// Add heading to page containing TOC
tocPage.Paragraphs.Add(heading2);
}
// Save the updated document
doc.Save(outFile);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Create Pdf Document
Document document = new Document();
// Get Content for work with TaggedPdf
ITaggedContent taggedContent = document.TaggedContent;
// Set Title and Language for Documnet
taggedContent.SetTitle("Tagged Pdf Document");
taggedContent.SetLanguage("en-US");
// Create Logical Structure Elements
SectElement sect = taggedContent.CreateSectElement();
taggedContent.RootElement.AppendChild(sect);
ParagraphElement p1 = taggedContent.CreateParagraphElement();
ParagraphElement p2 = taggedContent.CreateParagraphElement();
ParagraphElement p3 = taggedContent.CreateParagraphElement();
ParagraphElement p4 = taggedContent.CreateParagraphElement();
p1.SetText("P1. ");
p2.SetText("P2. ");
p3.SetText("P3. ");
p4.SetText("P4. ");
p1.SetTag("P1");
p2.SetTag("Para");
p3.SetTag("Para");
p4.SetTag("Paragraph");
sect.AppendChild(p1);
sect.AppendChild(p2);
sect.AppendChild(p3);
sect.AppendChild(p4);
SpanElement span1 = taggedContent.CreateSpanElement();
SpanElement span2 = taggedContent.CreateSpanElement();
SpanElement span3 = taggedContent.CreateSpanElement();
SpanElement span4 = taggedContent.CreateSpanElement();
span1.SetText("Span 1.");
span2.SetText("Span 2.");
span3.SetText("Span 3.");
span4.SetText("Span 4.");
span1.SetTag("SPAN");
span2.SetTag("Sp");
span3.SetTag("Sp");
span4.SetTag("TheSpan");
p1.AppendChild(span1);
p2.AppendChild(span2);
p3.AppendChild(span3);
p4.AppendChild(span4);
// Save Tagged Pdf Document
document.Save(dataDir + "CustomTag.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
Document doc = new Document(dataDir + "input.pdf");
// All fonts will be embedded as subset into document in case of SubsetAllFonts.
doc.FontUtilities.SubsetFonts(FontSubsetStrategy.SubsetAllFonts);
// Font subset will be embedded for fully embedded fonts but fonts which are not embedded into document will not be affected.
doc.FontUtilities.SubsetFonts(FontSubsetStrategy.SubsetEmbeddedFontsOnly);
doc.Save(dataDir + "Output_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Open document
Document pdfDocument = new Document(dataDir + "OptimizeDocument.pdf");
// Flatten annotations
foreach (var page in pdfDocument.Pages)
{
foreach (var annotation in page.Annotations)
{
annotation.Flatten();
}
}
// Save updated document
pdfDocument.Save(dataDir + "OptimizeDocument_out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
Document doc = new Document(dataDir + "input.pdf");
Aspose.Pdf.Text.Font[] fonts = doc.FontUtilities.GetAllFonts();
foreach (Aspose.Pdf.Text.Font font in fonts)
{
Console.WriteLine(font.FontName);
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
Document doc = new Document(dataDir + "input.pdf");
doc.FontSubstitution += new Document.FontSubstitutionHandler(OnFontSubstitution);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
Console.WriteLine(string.Format("Font '{0}' was substituted with another font '{1}'",
oldFont.FontName, newFont.FontName));
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
//Create pdf document
Aspose.Pdf.Document pdf = new Aspose.Pdf.Document();
//Bind XML and XSLT files to the document
try
{
pdf.BindXml(dataDir + "\\HelloWorld.xml", dataDir + "\\HelloWorld.xslt");
}
catch (System.Exception)
{
throw;
}
//Save the document
pdf.Save(dataDir + "HelloWorldUsingXmlAndXslt.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Create Pdf Document
Document document = new Document();
// Get Content for work with TaggedPdf
ITaggedContent taggedContent = document.TaggedContent;
// Set Title and Language for Documnet
taggedContent.SetTitle("Tagged Pdf Document");
taggedContent.SetLanguage("en-US");
// Under Development
IllustrationElement figure1 = taggedContent.CreateFigureElement();
taggedContent.RootElement.AppendChild(figure1);
figure1.AlternativeText = "Figure One";
figure1.Title = "Image 1";
figure1.SetTag("Fig1");
figure1.SetImage("image.png");
// Save Tagged Pdf Document
document.Save(dataDir + "IllustrationStructureElements.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Create Pdf Document
Document document = new Document();
// Get Content for work with TaggedPdf
ITaggedContent taggedContent = document.TaggedContent;
// Set Title and Language for Documnet
taggedContent.SetTitle("Tagged Pdf Document");
taggedContent.SetLanguage("en-US");
// Get Root Structure Element
StructureElement rootElement = taggedContent.RootElement;
HeaderElement h1 = taggedContent.CreateHeaderElement(1);
HeaderElement h2 = taggedContent.CreateHeaderElement(2);
HeaderElement h3 = taggedContent.CreateHeaderElement(3);
HeaderElement h4 = taggedContent.CreateHeaderElement(4);
HeaderElement h5 = taggedContent.CreateHeaderElement(5);
HeaderElement h6 = taggedContent.CreateHeaderElement(6);
rootElement.AppendChild(h1);
rootElement.AppendChild(h2);
rootElement.AppendChild(h3);
rootElement.AppendChild(h4);
rootElement.AppendChild(h5);
rootElement.AppendChild(h6);
SpanElement spanH11 = taggedContent.CreateSpanElement();
spanH11.SetText("H1. ");
h1.AppendChild(spanH11);
SpanElement spanH12 = taggedContent.CreateSpanElement();
spanH12.SetText("Level 1 Header");
h1.AppendChild(spanH12);
SpanElement spanH21 = taggedContent.CreateSpanElement();
spanH21.SetText("H2. ");
h2.AppendChild(spanH21);
SpanElement spanH22 = taggedContent.CreateSpanElement();
spanH22.SetText("Level 2 Header");
h2.AppendChild(spanH22);
SpanElement spanH31 = taggedContent.CreateSpanElement();
spanH31.SetText("H3. ");
h3.AppendChild(spanH31);
SpanElement spanH32 = taggedContent.CreateSpanElement();
spanH32.SetText("Level 3 Header");
h3.AppendChild(spanH32);
SpanElement spanH41 = taggedContent.CreateSpanElement();
spanH41.SetText("H4. ");
h4.AppendChild(spanH41);
SpanElement spanH42 = taggedContent.CreateSpanElement();
spanH42.SetText("Level 4 Header");
h4.AppendChild(spanH42);
SpanElement spanH51 = taggedContent.CreateSpanElement();
spanH51.SetText("H5. ");
h5.AppendChild(spanH51);
SpanElement spanH52 = taggedContent.CreateSpanElement();
spanH52.SetText("Level 5 Header");
h5.AppendChild(spanH52);
SpanElement spanH61 = taggedContent.CreateSpanElement();
spanH61.SetText("H6. ");
h6.AppendChild(spanH61);
SpanElement spanH62 = taggedContent.CreateSpanElement();
spanH62.SetText("Level 6 Header");
h6.AppendChild(spanH62);
ParagraphElement p = taggedContent.CreateParagraphElement();
p.SetText("P. ");
rootElement.AppendChild(p);
SpanElement span1 = taggedContent.CreateSpanElement();
span1.SetText("Lorem ipsum dolor sit amet, consectetur adipiscing elit. ");
p.AppendChild(span1);
SpanElement span2 = taggedContent.CreateSpanElement();
span2.SetText("Aenean nec lectus ac sem faucibus imperdiet. ");
p.AppendChild(span2);
SpanElement span3 = taggedContent.CreateSpanElement();
span3.SetText("Sed ut erat ac magna ullamcorper hendrerit. ");
p.AppendChild(span3);
SpanElement span4 = taggedContent.CreateSpanElement();
span4.SetText("Cras pellentesque libero semper, gravida magna sed, luctus leo. ");
p.AppendChild(span4);
SpanElement span5 = taggedContent.CreateSpanElement();
span5.SetText("Fusce lectus odio, laoreet nec ullamcorper ut, molestie eu elit. ");
p.AppendChild(span5);
SpanElement span6 = taggedContent.CreateSpanElement();
span6.SetText("Interdum et malesuada fames ac ante ipsum primis in faucibus. ");
p.AppendChild(span6);
SpanElement span7 = taggedContent.CreateSpanElement();
span7.SetText("Aliquam lacinia sit amet elit ac consectetur. Donec cursus condimentum ligula, vitae volutpat sem tristique eget. ");
p.AppendChild(span7);
SpanElement span8 = taggedContent.CreateSpanElement();
span8.SetText("Nulla in consectetur massa. Vestibulum vitae lobortis ante. Nulla ullamcorper pellentesque justo rhoncus accumsan. ");
p.AppendChild(span8);
SpanElement span9 = taggedContent.CreateSpanElement();
span9.SetText("Mauris ornare eu odio non lacinia. Aliquam massa leo, rhoncus ac iaculis eget, tempus et magna. Sed non consectetur elit. ");
p.AppendChild(span9);
SpanElement span10 = taggedContent.CreateSpanElement();
span10.SetText("Sed vulputate, quam sed lacinia luctus, ipsum nibh fringilla purus, vitae posuere risus odio id massa. Cras sed venenatis lacus.");
p.AppendChild(span10);
// Save Tagged Pdf Document
document.Save(dataDir + "InlineStructureElements.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Open document
Document pdfDocument = new Document(dataDir + "OptimizeDocument.pdf");
// Set LinkDuplcateStreams option
var optimizeOptions = new Pdf.Optimization.OptimizationOptions
{
LinkDuplcateStreams = true
};
// Optimize PDF document using OptimizationOptions
pdfDocument.OptimizeResources(optimizeOptions);
dataDir = dataDir + "OptimizeDocument_out.pdf";
// Save updated document
pdfDocument.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Open document
Document pdfDocument = new Document(dataDir + "OptimizeDocument.pdf");
// Set RemoveUsedObject option
var optimizeOptions = new Pdf.Optimization.OptimizationOptions
{
RemoveUnusedObjects = true
};
// Optimize PDF document using OptimizationOptions
pdfDocument.OptimizeResources(optimizeOptions);
dataDir = dataDir + "OptimizeDocument_out.pdf";
// Save updated document
pdfDocument.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Open document
Document pdfDocument = new Document(dataDir + "OptimizeDocument.pdf");
// Set RemoveUsedStreams option
var optimizeOptions = new Pdf.Optimization.OptimizationOptions
{
RemoveUnusedStreams = true
};
// Optimize PDF document using OptimizationOptions
pdfDocument.OptimizeResources(optimizeOptions);
dataDir = dataDir + "OptimizeDocument_out.pdf";
// Save updated document
pdfDocument.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Create Pdf Document
Document document = new Document();
// Get Content for work with TaggedPdf
ITaggedContent taggedContent = document.TaggedContent;
// Set Title and Language for Documnet
taggedContent.SetTitle("Tagged Pdf Document");
taggedContent.SetLanguage("en-US");
// Properties StructTreeRootElement and RootElement are used for access to
// StructTreeRoot object of pdf document and to root structure element (Document structure element).
StructTreeRootElement structTreeRootElement = taggedContent.StructTreeRootElement;
StructureElement rootElement = taggedContent.RootElement;
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Load an existing PDF document with missing font
string documentName = dataDir + "input.pdf";
string newName = "Arial";
using (System.IO.FileStream fs = new System.IO.FileStream(documentName, System.IO.FileMode.Open))
using (Document document = new Document(fs))
{
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
// Specify Default Font Name
pdfSaveOptions.DefaultFontName = newName;
document.Save(dataDir + "output_out.pdf", pdfSaveOptions);
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
using (Document doc = new Document())
{
doc.Pages.Add();
doc.Duplex = PrintDuplex.DuplexFlipLongEdge;
doc.Save(dataDir + "35297_out.pdf", SaveFormat.Pdf);
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
string outputFile = dataDir + "input.pdf";
using (PdfContentEditor ed = new PdfContentEditor())
{
ed.BindPdf(outputFile);
if ((ed.GetViewerPreference() & ViewerPreference.DuplexFlipShortEdge) > 0)
{
Console.WriteLine("The file has duplex flip short edge");
}
ed.ChangeViewerPreference(ViewerPreference.DuplexFlipShortEdge);
ed.Save(dataDir + "SetPrintDlgPropertiesUsingPdfContentEditor_out.pdf");
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Open document
Document pdfDocument = new Document(dataDir + "ShrinkDocument.pdf");
// Optimize PDF document. Note, though, that this method cannot guarantee document shrinking
pdfDocument.OptimizeResources();
dataDir = dataDir + "ShrinkDocument_out.pdf";
// Save updated document
pdfDocument.Save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Create Pdf Document
Document document = new Document();
// Get Content for work with TaggedPdf
ITaggedContent taggedContent = document.TaggedContent;
// Set Title and Language for Documnet
taggedContent.SetTitle("Tagged Pdf Document");
taggedContent.SetLanguage("en-US");
// Create Structure Elements
StructureElement rootElement = taggedContent.RootElement;
SectElement sect = taggedContent.CreateSectElement();
rootElement.AppendChild(sect);
HeaderElement h1 = taggedContent.CreateHeaderElement(1);
sect.AppendChild(h1);
h1.SetText("The Header");
h1.Title = "Title";
h1.Language = "en-US";
h1.AlternativeText = "Alternative Text";
h1.ExpansionText = "Expansion Text";
h1.ActualText = "Actual Text";
// Save Tagged Pdf Document
document.Save(dataDir + "StructureElementsProperties.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Create Pdf Document
Document document = new Document();
// Get Content for work with TaggedPdf
ITaggedContent taggedContent = document.TaggedContent;
// Set Title and Language for Documnet
taggedContent.SetTitle("Tagged Pdf Document");
taggedContent.SetLanguage("en-US");
ParagraphElement p = taggedContent.CreateParagraphElement();
taggedContent.RootElement.AppendChild(p);
// Under Development
p.StructureTextState.FontSize = 18F;
p.StructureTextState.ForegroundColor = Color.Red;
p.StructureTextState.FontStyle = FontStyles.Italic;
p.SetText("Red italic text.");
// Save Tagged Pdf Document
document.Save(dataDir + "StyleTextStructure.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Create Pdf Document
Document document = new Document();
// Get Content for work with TaggedPdf
ITaggedContent taggedContent = document.TaggedContent;
//
// Work with Tagged Pdf content
//
// Set Title and Language for Documnet
taggedContent.SetTitle("Simple Tagged Pdf Document");
taggedContent.SetLanguage("en-US");
// Save Tagged Pdf Document
document.Save(dataDir + "TaggedPDFContent.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Create Pdf Document
Document document = new Document();
// Get Content for work with TaggedPdf
ITaggedContent taggedContent = document.TaggedContent;
// Set Title and Language for Documnet
taggedContent.SetTitle("Tagged Pdf Document");
taggedContent.SetLanguage("en-US");
// Get Root Structure Element
StructureElement rootElement = taggedContent.RootElement;
HeaderElement h1 = taggedContent.CreateHeaderElement(1);
HeaderElement h2 = taggedContent.CreateHeaderElement(2);
HeaderElement h3 = taggedContent.CreateHeaderElement(3);
HeaderElement h4 = taggedContent.CreateHeaderElement(4);
HeaderElement h5 = taggedContent.CreateHeaderElement(5);
HeaderElement h6 = taggedContent.CreateHeaderElement(6);
h1.SetText("H1. Header of Level 1");
h2.SetText("H2. Header of Level 2");
h3.SetText("H3. Header of Level 3");
h4.SetText("H4. Header of Level 4");
h5.SetText("H5. Header of Level 5");
h6.SetText("H6. Header of Level 6");
rootElement.AppendChild(h1);
rootElement.AppendChild(h2);
rootElement.AppendChild(h3);
rootElement.AppendChild(h4);
rootElement.AppendChild(h5);
rootElement.AppendChild(h6);
ParagraphElement p = taggedContent.CreateParagraphElement();
p.SetText("P. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean nec lectus ac sem faucibus imperdiet. Sed ut erat ac magna ullamcorper hendrerit. Cras pellentesque libero semper, gravida magna sed, luctus leo. Fusce lectus odio, laoreet nec ullamcorper ut, molestie eu elit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aliquam lacinia sit amet elit ac consectetur. Donec cursus condimentum ligula, vitae volutpat sem tristique eget. Nulla in consectetur massa. Vestibulum vitae lobortis ante. Nulla ullamcorper pellentesque justo rhoncus accumsan. Mauris ornare eu odio non lacinia. Aliquam massa leo, rhoncus ac iaculis eget, tempus et magna. Sed non consectetur elit. Sed vulputate, quam sed lacinia luctus, ipsum nibh fringilla purus, vitae posuere risus odio id massa. Cras sed venenatis lacus.");
rootElement.AppendChild(p);
// Save Tagged Pdf Document
document.Save(dataDir + "TextBlockStructureElements.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Create Pdf Document
Document document = new Document();
// Get Content for work with TaggedPdf
ITaggedContent taggedContent = document.TaggedContent;
// Set Title and Language for Documnet
taggedContent.SetTitle("Tagged Pdf Document");
taggedContent.SetLanguage("en-US");
// Get Root Structure Elements
StructureElement rootElement = taggedContent.RootElement;
ParagraphElement p = taggedContent.CreateParagraphElement();
// Set Text to Text Structure Element
p.SetText("Paragraph.");
rootElement.AppendChild(p);
// Save Tagged Pdf Document
document.Save(dataDir + "TextStructureElement.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Open document
Document pdfDocument = new Document(dataDir + "OptimizeDocument.pdf");
// Set UnembedFonts option
var optimizeOptions = new Pdf.Optimization.OptimizationOptions
{
UnembedFonts = true
};
Console.WriteLine("Start");
// Optimize PDF document using OptimizationOptions
pdfDocument.OptimizeResources(optimizeOptions);
// Save updated document
pdfDocument.Save(dataDir + "OptimizeDocument_out.pdf");
Console.WriteLine("Finished");
var fi1 = new System.IO.FileInfo(dataDir + "OptimizeDocument.pdf");
var fi2 = new System.IO.FileInfo(dataDir + "OptimizeDocument_out.pdf");
Console.WriteLine("Original file size: {0}. Reduced file size: {1}", fi1.Length, fi2.Length);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Open document
Document pdfDocument = new Document(dataDir + "ValidatePDFUAStandard.pdf");
// Validate PDF for PDF/UA
bool isValidPdfUa = pdfDocument.Validate(dataDir + "validation-result-UA.xml", PdfFormat.PDF_UA_1);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
string outFile = dataDir + "AddStructureElementIntoElement_Output.pdf";
string logFile = dataDir + "46144_log.xml";
// Creation document and getting Tagged Pdf Content
Document document = new Document();
ITaggedContent taggedContent = document.TaggedContent;
// Setting Title and Nature Language for document
taggedContent.SetTitle("Text Elements Example");
taggedContent.SetLanguage("en-US");
// Getting Root structure element (Document structure element)
StructureElement rootElement = taggedContent.RootElement;
ParagraphElement p1 = taggedContent.CreateParagraphElement();
rootElement.AppendChild(p1);
SpanElement span11 = taggedContent.CreateSpanElement();
span11.SetText("Span_11");
SpanElement span12 = taggedContent.CreateSpanElement();
span12.SetText(" and Span_12.");
p1.SetText("Paragraph with ");
p1.AppendChild(span11);
p1.AppendChild(span12);
ParagraphElement p2 = taggedContent.CreateParagraphElement();
rootElement.AppendChild(p2);
SpanElement span21 = taggedContent.CreateSpanElement();
span21.SetText("Span_21");
SpanElement span22 = taggedContent.CreateSpanElement();
span22.SetText("Span_22.");
p2.AppendChild(span21);
p2.SetText(" and ");
p2.AppendChild(span22);
ParagraphElement p3 = taggedContent.CreateParagraphElement();
rootElement.AppendChild(p3);
SpanElement span31 = taggedContent.CreateSpanElement();
span31.SetText("Span_31");
SpanElement span32 = taggedContent.CreateSpanElement();
span32.SetText(" and Span_32");
p3.AppendChild(span31);
p3.AppendChild(span32);
p3.SetText(".");
ParagraphElement p4 = taggedContent.CreateParagraphElement();
rootElement.AppendChild(p4);
SpanElement span41 = taggedContent.CreateSpanElement();
SpanElement span411 = taggedContent.CreateSpanElement();
span411.SetText("Span_411, ");
span41.SetText("Span_41, ");
span41.AppendChild(span411);
SpanElement span42 = taggedContent.CreateSpanElement();
SpanElement span421 = taggedContent.CreateSpanElement();
span421.SetText("Span 421 and ");
span42.AppendChild(span421);
span42.SetText("Span_42");
p4.AppendChild(span41);
p4.AppendChild(span42);
p4.SetText(".");
// Save Tagged Pdf Document
document.Save(outFile);
// Checking PDF/UA compliance
document = new Document(outFile);
bool isPdfUaCompliance = document.Validate(logFile, PdfFormat.PDF_UA_1);
Console.WriteLine(String.Format("PDF/UA compliance: {0}", isPdfUaCompliance));
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
string outFile = dataDir + "45929_doc.pdf";
string logFile = dataDir + "45929_log.xml";
// Create Pdf Document
Document document = new Document();
ITaggedContent taggedContent = document.TaggedContent;
taggedContent.SetTitle("Sample of Note Elements");
taggedContent.SetLanguage("en-US");
// Add Paragraph Element
ParagraphElement paragraph = taggedContent.CreateParagraphElement();
taggedContent.RootElement.AppendChild(paragraph);
// Add NoteElement
NoteElement note1 = taggedContent.CreateNoteElement();
paragraph.AppendChild(note1);
note1.SetText("Note with auto generate ID. ");
// Add NoteElement
NoteElement note2 = taggedContent.CreateNoteElement();
paragraph.AppendChild(note2);
note2.SetText("Note with ID = 'note_002'. ");
note2.SetId("note_002");
// Add NoteElement
NoteElement note3 = taggedContent.CreateNoteElement();
paragraph.AppendChild(note3);
note3.SetText("Note with ID = 'note_003'. ");
note3.SetId("note_003");
// Must throw exception - Aspose.Pdf.Tagged.TaggedException : Structure element with ID='note_002' already exists
//note3.SetId("note_002");
// Resultant document does not compliance to PDF/UA If ClearId() used for Note Structure Element
//note3.ClearId();
// Save Tagged Pdf Document
document.Save(outFile);
// Checking PDF/UA compliance
document = new Document(outFile);
bool isPdfUaCompliance = document.Validate(logFile, PdfFormat.PDF_UA_1);
Console.WriteLine(String.Format("PDF/UA compliance: {0}", isPdfUaCompliance));
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Create document
Document document = new Document();
ITaggedContent taggedContent = document.TaggedContent;
taggedContent.SetTitle("Example table");
taggedContent.SetLanguage("en-US");
// Get root structure element
StructureElement rootElement = taggedContent.RootElement;
TableElement tableElement = taggedContent.CreateTableElement();
rootElement.AppendChild(tableElement);
tableElement.Border = new BorderInfo(BorderSide.All, 1.2F, Color.DarkBlue);
TableTHeadElement tableTHeadElement = tableElement.CreateTHead();
TableTBodyElement tableTBodyElement = tableElement.CreateTBody();
TableTFootElement tableTFootElement = tableElement.CreateTFoot();
int rowCount = 50;
int colCount = 4;
int rowIndex;
int colIndex;
TableTRElement headTrElement = tableTHeadElement.CreateTR();
headTrElement.AlternativeText = "Head Row";
headTrElement.BackgroundColor = Color.LightGray;
for (colIndex = 0; colIndex < colCount; colIndex++)
{
TableTHElement thElement = headTrElement.CreateTH();
thElement.SetText(String.Format("Head {0}", colIndex));
thElement.BackgroundColor = Color.GreenYellow;
thElement.Border = new BorderInfo(BorderSide.All, 4.0F, Color.Gray);
thElement.IsNoBorder = true;
thElement.Margin = new MarginInfo(16.0, 2.0, 8.0, 2.0);
thElement.Alignment = HorizontalAlignment.Right;
}
for (rowIndex = 0; rowIndex < rowCount; rowIndex++)
{
TableTRElement trElement = tableTBodyElement.CreateTR();
trElement.AlternativeText = String.Format("Row {0}", rowIndex);
for (colIndex = 0; colIndex < colCount; colIndex++)
{
int colSpan = 1;
int rowSpan = 1;
if (colIndex == 1 && rowIndex == 1)
{
colSpan = 2;
rowSpan = 2;
}
else if (colIndex == 2 && (rowIndex == 1 || rowIndex == 2))
{
continue;
}
else if (rowIndex == 2 && (colIndex == 1 || colIndex == 2))
{
continue;
}
TableTDElement tdElement = trElement.CreateTD();
tdElement.SetText(String.Format("Cell [{0}, {1}]", rowIndex, colIndex));
tdElement.BackgroundColor = Color.Yellow;
tdElement.Border = new BorderInfo(BorderSide.All, 4.0F, Color.Gray);
tdElement.IsNoBorder = false;
tdElement.Margin = new MarginInfo(8.0, 2.0, 8.0, 2.0);
tdElement.Alignment = HorizontalAlignment.Center;
TextState cellTextState = new TextState();
cellTextState.ForegroundColor = Color.DarkBlue;
cellTextState.FontSize = 7.5F;
cellTextState.FontStyle = FontStyles.Bold;
cellTextState.Font = FontRepository.FindFont("Arial");
tdElement.DefaultCellTextState = cellTextState;
tdElement.IsWordWrapped = true;
tdElement.VerticalAlignment = VerticalAlignment.Center;
tdElement.ColSpan = colSpan;
tdElement.RowSpan = rowSpan;
}
}
TableTRElement footTrElement = tableTFootElement.CreateTR();
footTrElement.AlternativeText = "Foot Row";
footTrElement.BackgroundColor = Color.LightSeaGreen;
for (colIndex = 0; colIndex < colCount; colIndex++)
{
TableTDElement tdElement = footTrElement.CreateTD();
tdElement.SetText(String.Format("Foot {0}", colIndex));
tdElement.Alignment = HorizontalAlignment.Center;
tdElement.StructureTextState.FontSize = 7F;
tdElement.StructureTextState.FontStyle = FontStyles.Bold;
}
StructureAttributes tableAttributes = tableElement.Attributes.GetAttributes(AttributeOwnerStandard.Table);
StructureAttribute summaryAttribute = new StructureAttribute(AttributeKey.Summary);
summaryAttribute.SetStringValue("The summary text for table");
tableAttributes.SetAttribute(summaryAttribute);
// Save Tagged Pdf Document
document.Save(dataDir + "CreateTableElement.pdf");
// Checking PDF/UA compliance
document = new Document(dataDir + "CreateTableElement.pdf");
bool isPdfUaCompliance = document.Validate(dataDir + "table.xml", PdfFormat.PDF_UA_1);
Console.WriteLine(String.Format("PDF/UA compliance: {0}", isPdfUaCompliance));
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
string outFile = dataDir + "LinkStructureElements_Output.pdf";
string logFile = dataDir + "46035_log.xml";
string imgFile = dataDir + "google-icon-512.png";
// Creation document and getting Tagged Pdf Content
Document document = new Document();
ITaggedContent taggedContent = document.TaggedContent;
// Setting Title and Nature Language for document
taggedContent.SetTitle("Link Elements Example");
taggedContent.SetLanguage("en-US");
// Getting Root structure element (Document structure element)
StructureElement rootElement = taggedContent.RootElement;
ParagraphElement p1 = taggedContent.CreateParagraphElement();
rootElement.AppendChild(p1);
LinkElement link1 = taggedContent.CreateLinkElement();
p1.AppendChild(link1);
link1.Hyperlink = new WebHyperlink("http://google.com");
link1.SetText("Google");
link1.AlternateDescriptions = "Link to Google";
ParagraphElement p2 = taggedContent.CreateParagraphElement();
rootElement.AppendChild(p2);
LinkElement link2 = taggedContent.CreateLinkElement();
p2.AppendChild(link2);
link2.Hyperlink = new WebHyperlink("http://google.com");
SpanElement span2 = taggedContent.CreateSpanElement();
span2.SetText("Google");
link2.AppendChild(span2);
link2.AlternateDescriptions = "Link to Google";
ParagraphElement p3 = taggedContent.CreateParagraphElement();
rootElement.AppendChild(p3);
LinkElement link3 = taggedContent.CreateLinkElement();
p3.AppendChild(link3);
link3.Hyperlink = new WebHyperlink("http://google.com");
SpanElement span31 = taggedContent.CreateSpanElement();
span31.SetText("G");
SpanElement span32 = taggedContent.CreateSpanElement();
span32.SetText("oogle");
link3.AppendChild(span31);
link3.SetText("-");
link3.AppendChild(span32);
link3.AlternateDescriptions = "Link to Google";
ParagraphElement p4 = taggedContent.CreateParagraphElement();
rootElement.AppendChild(p4);
LinkElement link4 = taggedContent.CreateLinkElement();
p4.AppendChild(link4);
link4.Hyperlink = new WebHyperlink("http://google.com");
link4.SetText("The multiline link: Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google Google");
link4.AlternateDescriptions = "Link to Google (multiline)";
ParagraphElement p5 = taggedContent.CreateParagraphElement();
rootElement.AppendChild(p5);
LinkElement link5 = taggedContent.CreateLinkElement();
p5.AppendChild(link5);
link5.Hyperlink = new WebHyperlink("http://google.com");
FigureElement figure5 = taggedContent.CreateFigureElement();
figure5.SetImage(imgFile, 1200);
figure5.AlternativeText = "Google icon";
StructureAttributes linkLayoutAttributes = link5.Attributes.GetAttributes(AttributeOwnerStandard.Layout);
StructureAttribute placementAttribute = new StructureAttribute(AttributeKey.Placement);
placementAttribute.SetNameValue(AttributeName.Placement_Block);
linkLayoutAttributes.SetAttribute(placementAttribute);
link5.AppendChild(figure5);
link5.AlternateDescriptions = "Link to Google";
// Save Tagged Pdf Document
document.Save(outFile);
// Checking PDF/UA compliance
document = new Document(outFile);
bool isPdfUaCompliance = document.Validate(logFile, PdfFormat.PDF_UA_1);
Console.WriteLine(String.Format("PDF/UA compliance: {0}", isPdfUaCompliance));
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
Document document = new Document();
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Get TaggedContent
Tagged.ITaggedContent taggedContent = document.TaggedContent;
// Set Title and Language
taggedContent.SetTitle("Example Tagged Document");
taggedContent.SetLanguage("en-US");
// Header (en-US, inherited from document)
LogicalStructure.HeaderElement h1 = taggedContent.CreateHeaderElement(1);
h1.SetText("Phrase on different languages");
taggedContent.RootElement.AppendChild(h1);
// Paragraph (English)
LogicalStructure.ParagraphElement pEN = taggedContent.CreateParagraphElement();
pEN.SetText("Hello, World!");
pEN.Language = "en-US";
taggedContent.RootElement.AppendChild(pEN);
// Paragraph (German)
LogicalStructure.ParagraphElement pDE = taggedContent.CreateParagraphElement();
pDE.SetText("Hallo Welt!");
pDE.Language = "de-DE";
taggedContent.RootElement.AppendChild(pDE);
// Paragraph (French)
LogicalStructure.ParagraphElement pFR = taggedContent.CreateParagraphElement();
pFR.SetText("Bonjour le monde!");
pFR.Language = "fr-FR";
taggedContent.RootElement.AppendChild(pFR);
// Paragraph (Spanish)
LogicalStructure.ParagraphElement pSP = taggedContent.CreateParagraphElement();
pSP.SetText("¡Hola Mundo!");
pSP.Language = "es-ES";
taggedContent.RootElement.AppendChild(pSP);
// Save Tagged Pdf Document
document.Save(dataDir + "SetupLanguageAndTitle.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Create document
Document document = new Document();
ITaggedContent taggedContent = document.TaggedContent;
taggedContent.SetTitle("Example table cell style");
taggedContent.SetLanguage("en-US");
// Get root structure element
StructureElement rootElement = taggedContent.RootElement;
// Create table structure element
TableElement tableElement = taggedContent.CreateTableElement();
rootElement.AppendChild(tableElement);
TableTHeadElement tableTHeadElement = tableElement.CreateTHead();
TableTBodyElement tableTBodyElement = tableElement.CreateTBody();
TableTFootElement tableTFootElement = tableElement.CreateTFoot();
int rowCount = 4;
int colCount = 4;
int rowIndex;
int colIndex;
TableTRElement headTrElement = tableTHeadElement.CreateTR();
headTrElement.AlternativeText = "Head Row";
for (colIndex = 0; colIndex < colCount; colIndex++)
{
TableTHElement thElement = headTrElement.CreateTH();
thElement.SetText(String.Format("Head {0}", colIndex));
thElement.BackgroundColor = Color.GreenYellow;
thElement.Border = new BorderInfo(BorderSide.All, 4.0F, Color.Gray);
thElement.IsNoBorder = true;
thElement.Margin = new MarginInfo(16.0, 2.0, 8.0, 2.0);
thElement.Alignment = HorizontalAlignment.Right;
}
for (rowIndex = 0; rowIndex < rowCount; rowIndex++)
{
TableTRElement trElement = tableTBodyElement.CreateTR();
trElement.AlternativeText = String.Format("Row {0}", rowIndex);
for (colIndex = 0; colIndex < colCount; colIndex++)
{
int colSpan = 1;
int rowSpan = 1;
if (colIndex == 1 && rowIndex == 1)
{
colSpan = 2;
rowSpan = 2;
}
else if (colIndex == 2 && (rowIndex == 1 || rowIndex == 2))
{
continue;
}
else if (rowIndex == 2 && (colIndex == 1 || colIndex == 2))
{
continue;
}
TableTDElement tdElement = trElement.CreateTD();
tdElement.SetText(String.Format("Cell [{0}, {1}]", rowIndex, colIndex));
tdElement.BackgroundColor = Color.Yellow;
tdElement.Border = new BorderInfo(BorderSide.All, 4.0F, Color.Gray);
tdElement.IsNoBorder = false;
tdElement.Margin = new MarginInfo(8.0, 2.0, 8.0, 2.0);
tdElement.Alignment = HorizontalAlignment.Center;
TextState cellTextState = new TextState();
cellTextState.ForegroundColor = Color.DarkBlue;
cellTextState.FontSize = 7.5F;
cellTextState.FontStyle = FontStyles.Bold;
cellTextState.Font = FontRepository.FindFont("Arial");
tdElement.DefaultCellTextState = cellTextState;
tdElement.IsWordWrapped = true;
tdElement.VerticalAlignment = VerticalAlignment.Center;
tdElement.ColSpan = colSpan;
tdElement.RowSpan = rowSpan;
}
}
TableTRElement footTrElement = tableTFootElement.CreateTR();
footTrElement.AlternativeText = "Foot Row";
for (colIndex = 0; colIndex < colCount; colIndex++)
{
TableTDElement tdElement = footTrElement.CreateTD();
tdElement.SetText(String.Format("Foot {0}", colIndex));
}
// Save Tagged Pdf Document
document.Save(dataDir + "StyleTableCell.pdf");
// Checking PDF/UA compliance
document = new Document(dataDir + "StyleTableCell.pdf");
bool isPdfUaCompliance = document.Validate(dataDir + "StyleTableCell.xml", PdfFormat.PDF_UA_1);
Console.WriteLine(String.Format("PDF/UA compliance: {0}", isPdfUaCompliance));
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Create document
Document document = new Document();
ITaggedContent taggedContent = document.TaggedContent;
taggedContent.SetTitle("Example table style");
taggedContent.SetLanguage("en-US");
// Get root structure element
StructureElement rootElement = taggedContent.RootElement;
// Create table structure element
TableElement tableElement = taggedContent.CreateTableElement();
rootElement.AppendChild(tableElement);
tableElement.BackgroundColor = Color.Beige;
tableElement.Border = new BorderInfo(BorderSide.All, 0.80F, Color.Gray);
tableElement.Alignment = HorizontalAlignment.Center;
tableElement.Broken = TableBroken.Vertical;
tableElement.ColumnAdjustment = ColumnAdjustment.AutoFitToWindow;
tableElement.ColumnWidths = "80 80 80 80 80";
tableElement.DefaultCellBorder = new BorderInfo(BorderSide.All, 0.50F, Color.DarkBlue);
tableElement.DefaultCellPadding = new MarginInfo(16.0, 2.0, 8.0, 2.0);
tableElement.DefaultCellTextState.ForegroundColor = Color.DarkCyan;
tableElement.DefaultCellTextState.FontSize = 8F;
tableElement.DefaultColumnWidth = "70";
tableElement.IsBroken = false;
tableElement.IsBordersIncluded = true;
tableElement.Left = 0F;
tableElement.Top = 40F;
tableElement.RepeatingColumnsCount = 2;
tableElement.RepeatingRowsCount = 3;
TextState rowStyle = new TextState();
rowStyle.BackgroundColor = Color.LightCoral;
tableElement.RepeatingRowsStyle = rowStyle;
TableTHeadElement tableTHeadElement = tableElement.CreateTHead();
TableTBodyElement tableTBodyElement = tableElement.CreateTBody();
TableTFootElement tableTFootElement = tableElement.CreateTFoot();
int rowCount = 10;
int colCount = 5;
int rowIndex;
int colIndex;
TableTRElement headTrElement = tableTHeadElement.CreateTR();
headTrElement.AlternativeText = "Head Row";
for (colIndex = 0; colIndex < colCount; colIndex++)
{
TableTHElement thElement = headTrElement.CreateTH();
thElement.SetText(String.Format("Head {0}", colIndex));
}
for (rowIndex = 0; rowIndex < rowCount; rowIndex++)
{
TableTRElement trElement = tableTBodyElement.CreateTR();
trElement.AlternativeText = String.Format("Row {0}", rowIndex);
for (colIndex = 0; colIndex < colCount; colIndex++)
{
TableTDElement tdElement = trElement.CreateTD();
tdElement.SetText(String.Format("Cell [{0}, {1}]", rowIndex, colIndex));
}
}
TableTRElement footTrElement = tableTFootElement.CreateTR();
footTrElement.AlternativeText = "Foot Row";
for (colIndex = 0; colIndex < colCount; colIndex++)
{
TableTDElement tdElement = footTrElement.CreateTD();
tdElement.SetText(String.Format("Foot {0}", colIndex));
}
// Save Tagged Pdf Document
document.Save(dataDir + "StyleTableElement.pdf");
// Checking PDF/UA compliance
document = new Document(dataDir + "StyleTableElement.pdf");
bool isPdfUaCompliance = document.Validate(dataDir + "StyleTableElement.xml", PdfFormat.PDF_UA_1);
Console.WriteLine(String.Format("PDF/UA compliance: {0}", isPdfUaCompliance));
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Create document
Document document = new Document();
ITaggedContent taggedContent = document.TaggedContent;
taggedContent.SetTitle("Example table row style");
taggedContent.SetLanguage("en-US");
// Get root structure element
StructureElement rootElement = taggedContent.RootElement;
// Create table structure element
TableElement tableElement = taggedContent.CreateTableElement();
rootElement.AppendChild(tableElement);
TableTHeadElement tableTHeadElement = tableElement.CreateTHead();
TableTBodyElement tableTBodyElement = tableElement.CreateTBody();
TableTFootElement tableTFootElement = tableElement.CreateTFoot();
int rowCount = 7;
int colCount = 3;
int rowIndex;
int colIndex;
TableTRElement headTrElement = tableTHeadElement.CreateTR();
headTrElement.AlternativeText = "Head Row";
for (colIndex = 0; colIndex < colCount; colIndex++)
{
TableTHElement thElement = headTrElement.CreateTH();
thElement.SetText(String.Format("Head {0}", colIndex));
}
for (rowIndex = 0; rowIndex < rowCount; rowIndex++)
{
TableTRElement trElement = tableTBodyElement.CreateTR();
trElement.AlternativeText = String.Format("Row {0}", rowIndex);
trElement.BackgroundColor = Color.LightGoldenrodYellow;
trElement.Border = new BorderInfo(BorderSide.All, 0.75F, Color.DarkGray);
trElement.DefaultCellBorder = new BorderInfo(BorderSide.All, 0.50F, Color.Blue);
trElement.MinRowHeight = 100.0;
trElement.FixedRowHeight = 120.0;
trElement.IsInNewPage = (rowIndex % 3 == 1);
trElement.IsRowBroken = true;
TextState cellTextState = new TextState();
cellTextState.ForegroundColor = Color.Red;
trElement.DefaultCellTextState = cellTextState;
trElement.DefaultCellPadding = new MarginInfo(16.0, 2.0, 8.0, 2.0);
trElement.VerticalAlignment = VerticalAlignment.Bottom;
for (colIndex = 0; colIndex < colCount; colIndex++)
{
TableTDElement tdElement = trElement.CreateTD();
tdElement.SetText(String.Format("Cell [{0}, {1}]", rowIndex, colIndex));
}
}
TableTRElement footTrElement = tableTFootElement.CreateTR();
footTrElement.AlternativeText = "Foot Row";
for (colIndex = 0; colIndex < colCount; colIndex++)
{
TableTDElement tdElement = footTrElement.CreateTD();
tdElement.SetText(String.Format("Foot {0}", colIndex));
}
// Save Tagged Pdf Document
document.Save(dataDir + "StyleTableRow.pdf");
// Checking PDF/UA compliance
document = new Document(dataDir + "StyleTableRow.pdf");
bool isPdfUaCompliance = document.Validate(dataDir + "StyleTableRow.xml", PdfFormat.PDF_UA_1);
Console.WriteLine(String.Format("PDF/UA compliance: {0}", isPdfUaCompliance));
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
string inFile = dataDir + "TH.pdf";
string outFile = dataDir + "TH_out.pdf";
string logFile = dataDir + "TH_out.xml";
// Open document
Document document = new Document(inFile);
// Gets tagged content and root structure element
ITaggedContent taggedContent = document.TaggedContent;
StructureElement rootElement = taggedContent.RootElement;
// Set title for tagged pdf document
taggedContent.SetTitle("Document with images");
foreach (FigureElement figureElement in rootElement.FindElements<FigureElement>(true))
{
// Set Alternative Text for Figure
figureElement.AlternativeText = "Figure alternative text (technique 2)";
// Create and Set BBox Attribute
StructureAttribute bboxAttribute = new StructureAttribute(AttributeKey.BBox);
bboxAttribute.SetRectangleValue(new Rectangle(0.0, 0.0, 100.0, 100.0));
StructureAttributes figureLayoutAttributes = figureElement.Attributes.GetAttributes(AttributeOwnerStandard.Layout);
figureLayoutAttributes.SetAttribute(bboxAttribute);
}
// Move Span Element into Paragraph (find wrong span and paragraph in first TD)
TableElement tableElement = rootElement.FindElements<TableElement>(true)[0];
SpanElement spanElement = tableElement.FindElements<SpanElement>(true)[0];
TableTDElement firstTdElement = tableElement.FindElements<TableTDElement>(true)[0];
ParagraphElement paragraph = firstTdElement.FindElements<ParagraphElement>(true)[0];
// Move Span Element into Paragraph
spanElement.ChangeParentElement(paragraph);
// Save document
document.Save(outFile);
// Checking PDF/UA Compliance for out document
document = new Document(outFile);
bool isPdfUaCompliance = document.Validate(logFile, PdfFormat.PDF_UA_1);
Console.WriteLine(String.Format("PDF/UA compliance: {0}", isPdfUaCompliance));
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
string inputFileName = dataDir + "StructureElements.pdf";
string outputLogName = dataDir + "ua-20.xml";
using (var document = new Aspose.Pdf.Document(inputFileName))
{
bool isValid = document.Validate(outputLogName, Aspose.Pdf.PdfFormat.PDF_UA_1);
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
//Create pdf document
Aspose.Pdf.Document pdf = new Aspose.Pdf.Document();
//Bind XML and XSLT files to the document
pdf.BindXml(dataDir + "\\Breakfast.xml", dataDir + "\\Breakfast.xslt");
//Save the document
pdf.Save(dataDir + "BreakfastMenu.pdf");
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_SecuritySignatures();
string inPfxFile = dataDir + "certificate.pfx";
string inFile = dataDir + "input.pdf";
string outFile = dataDir + "output.pdf";
using (Aspose.Pdf.Facades.PdfFileSignature pdfSign = new Aspose.Pdf.Facades.PdfFileSignature())
{
pdfSign.BindPdf(inFile);
//create a rectangle for signature location
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(310, 45, 200, 50);
//create any of the three signature types
PKCS7 pkcs = new PKCS7(inPfxFile, "12345");
pkcs.Reason = "Pruebas Firma";
pkcs.ContactInfo = "Contacto Pruebas";
pkcs.Location = "Población (Provincia)";
pkcs.Date = DateTime.Now;
SignatureCustomAppearance signatureCustomAppearance = new SignatureCustomAppearance();
signatureCustomAppearance.DateSignedAtLabel = "Fecha";
signatureCustomAppearance.DigitalSignedLabel = "Digitalmente firmado por";
signatureCustomAppearance.ReasonLabel = "Razón";
signatureCustomAppearance.LocationLabel = "Localización";
signatureCustomAppearance.FontFamilyName = "Arial";
signatureCustomAppearance.FontSize = 10d;
signatureCustomAppearance.Culture = CultureInfo.InvariantCulture;
signatureCustomAppearance.DateTimeFormat = "yyyy.MM.dd HH:mm:ss";
pkcs.CustomAppearance = signatureCustomAppearance;
// sign the PDF file
pdfSign.Sign(1, true, rect, pkcs);
//save output PDF file
pdfSign.Save(outFile);
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_SecuritySignatures();
string inPfxFile = dataDir + "SampleCertificate.pfx";
string inFile = dataDir + "input.pdf";
string outFile = dataDir + "output.pdf";
using (PdfFileSignature pdfSign = new PdfFileSignature())
{
pdfSign.BindPdf(inFile);
//create a rectangle for signature location
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(310, 45, 200, 50);
//create any of the three signature types
PKCS7 pkcs = new PKCS7(inPfxFile, "idsrv3test");
SignatureCustomAppearance signatureCustomAppearance = new SignatureCustomAppearance();
signatureCustomAppearance.FontSize = 6;
signatureCustomAppearance.FontFamilyName = "Times New Roman";
signatureCustomAppearance.DigitalSignedLabel = "Signed by me";
pkcs.CustomAppearance = signatureCustomAppearance;
// sign the PDF file
pdfSign.Sign(1, true, rect, pkcs);
//save output PDF file
pdfSign.Save(outFile);
}
// For complete examples and data files, please go to https://github.com/aspose-pdf/Aspose.PDF-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_SecuritySignatures();
string inPfxFile = dataDir + "certificate.pfx";
string inFile = dataDir + "input.pdf";
string outFile = dataDir + "output.pdf";
using (Aspose.Pdf.Facades.PdfFileSignature pdfSign = new Aspose.Pdf.Facades.PdfFileSignature())
{
pdfSign.BindPdf(inFile);
//create a rectangle for signature location
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(100, 100, 200, 100);
//create any of the three signature types
PKCS1 signature = new PKCS1(inPfxFile, "12345");
// sign the PDF file
pdfSign.Sign(1, "", "Contact", "", true, rect, signature);
//save output PDF file
pdfSign.Save(outFile);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment