Class Document
Namespace: Aspose.Note
Assembly: Aspose.Note.dll (25.3.0)
Represents an Aspose.Note document.
public class Document : CompositeNode<page>, INode, ICompositeNode<page>, ICompositeNode, IEnumerable<page>, IEnumerable, INotebookChildNode
Inheritance
object ← Node ← CompositeNodeBase ← CompositeNode<page> ← Document
Implements
INode, ICompositeNode<page>, ICompositeNode, IEnumerable<page>, IEnumerable, INotebookChildNode
Inherited Members
CompositeNode<page>.GetEnumerator(), CompositeNode<page>.InsertChild<t1>(int, T1), CompositeNode<page>.InsertChildrenRange(int, IEnumerable<page>), CompositeNode<page>.InsertChildrenRange(int, params Page[]), CompositeNode<page>.AppendChildFirst<t1>(T1), CompositeNode<page>.AppendChildLast<t1>(T1), CompositeNode<page>.RemoveChild<t1>(T1), CompositeNode<page>.Accept(DocumentVisitor), CompositeNode<page>.GetChildNodes(NodeType), CompositeNode<page>.GetChildNodes<t1>(), CompositeNode<page>.IsComposite, CompositeNode<page>.FirstChild, CompositeNode<page>.LastChild, CompositeNodeBase.GetChildNodes(NodeType), CompositeNodeBase.GetChildNodes<t1>(), CompositeNodeBase.CheckDocument(Node), Node.Accept(DocumentVisitor), Node.Document, Node.IsComposite, Node.NodeType, Node.ParentNode, Node.PreviousSibling, Node.NextSibling, object.GetType(), object.MemberwiseClone(), object.ToString(), object.Equals(object?), object.Equals(object?, object?), object.ReferenceEquals(object?, object?), object.GetHashCode()
Examples
Send Document to Printer Using Default Options
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
var document = new Aspose.Note.Document(dataDir + "Aspose.one");
document.Print();
Save a Document to OneNote Format
string inputFile = "Sample1.one";
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string outputFile = "SaveDocToOneNoteFormat_out.one";
Document doc = new Document(dataDir + inputFile);
doc.Save(dataDir + outputFile);
Load an Encrypted Document
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
LoadOptions loadOptions = new LoadOptions { DocumentPassword = "password" };
Document doc = new Document(dataDir + "Sample1.one", loadOptions);
Save a Document with Encryption
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_NoteBook();
Document document = new Document();
document.Save(dataDir + "CreatingPasswordProtectedDoc_out.one", new OneSaveOptions() { DocumentPassword = "pass" });
Save Document Using SaveFormat Enumeration
string inputFile = "Sample1.one";
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string outputFile = "SaveDocToOneNoteFormatUsingSaveFormat_out.one";
Document document = new Document(dataDir + inputFile);
document.Save(dataDir + outputFile, SaveFormat.One);
Save Document Using OneSaveOptions
string inputFile = "Sample1.one";
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string outputFile = "SaveDocToOneNoteFormatUsingOneSaveOptions_out.one";
Document document = new Document(dataDir + inputFile);
document.Save(dataDir + outputFile, new OneSaveOptions());
Get Page Count of a Document
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Pages();
// Load the document into Aspose.Note.
Document oneFile = new Document(dataDir + "Aspose.one");
// Get number of pages.
int count = oneFile.Count();
// Print count on the output screen.
Console.WriteLine(count);
Save a Document in PDF Format (Default Settings)
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document oneFile = new Document(dataDir + "Aspose.one");
// Save the document as PDF.
dataDir = dataDir + "SaveWithDefaultSettings_out.pdf";
oneFile.Save(dataDir, SaveFormat.Pdf);
Save a Document in GIF Format
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document oneFile = new Document(dataDir + "Aspose.one");
dataDir = dataDir + "SaveToImageDefaultOptions_out.gif";
// Save the document as gif.
oneFile.Save(dataDir, SaveFormat.Gif);
Set Image Quality for JPEG Format
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document doc = new Document(dataDir + "Aspose.one");
dataDir = dataDir + "SetOutputImageResolution_out.jpg";
// Save the document.
doc.Save(dataDir, new ImageSaveOptions(SaveFormat.Jpeg) { Quality = 100 });
Set Image Resolution for Saving Document as Image
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document doc = new Document(dataDir + "Aspose.one");
dataDir = dataDir + "SetOutputImageResolution_out.jpg";
// Save the document.
doc.Save(dataDir, new ImageSaveOptions(SaveFormat.Jpeg) { Resolution = 220 });
Get File Format of a Document
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
var document = new Aspose.Note.Document(dataDir + "Aspose.one");
switch (document.FileFormat)
{
case FileFormat.OneNote2010:
// Process OneNote 2010
break;
case FileFormat.OneNoteOnline:
// Process OneNote Online
break;
}
Bind Hyperlink to an Image
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Images();
var document = new Document();
var page = new Page(document);
var image = new Image(document, dataDir + "image.jpg")
{
HyperlinkUrl = "http://image.com"
};
page.AppendChildLast(image);
document.AppendChildLast(page);
document.Save(dataDir + "Image with Hyperlink_out.one");
Save a Document to a Stream in PDF Format
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document doc = new Document(dataDir + "Aspose.one");
MemoryStream dstStream = new MemoryStream();
doc.Save(dstStream, SaveFormat.Pdf);
// Rewind the stream position back to zero so it is ready for the next reader.
dstStream.Seek(0, SeekOrigin.Begin);
Check if a Document is Password-Protected
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fileName = Path.Combine(dataDir, "Aspose.one");
Document document;
if (!Document.IsEncrypted(fileName, out document))
{
Console.WriteLine("The document is loaded and ready to be processed.");
}
else
{
Console.WriteLine("The document is encrypted. Provide a password.");
}
Add New Section to a Notebook
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_NoteBook();
// Load a OneNote Notebook.
var notebook = new Notebook(dataDir + "Notizbuch ffnen.onetoc2");
// Append a new child to the Notebook.
notebook.AppendChild(new Document(dataDir + "Neuer Abschnitt 1.one"));
dataDir = dataDir + "AddChildNode_out.onetoc2";
// Save the Notebook.
notebook.Save(dataDir);
Handle Unsupported OneNote 2007 Format
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fileName = Path.Combine(dataDir, "OneNote2007.one");
try
{
new Document(fileName);
}
catch (UnsupportedFileFormatException e)
{
if (e.FileFormat == FileFormat.OneNote2007)
{
Console.WriteLine("It looks like the provided file is in OneNote 2007 format that is not supported.");
}
else
{
throw;
}
}
Restore Previous Version of a Page
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Pages();
// Load OneNote document and get the first child.
Document document = new Document(dataDir + "Aspose.one");
Page page = document.FirstChild;
Page previousPageVersion = document.GetPageHistory(page).Last();
document.RemoveChild(page);
document.AppendChildLast(previousPageVersion);
document.Save(dataDir + "RollBackRevisions_out.one");
Clone a Page (With and Without History)
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Pages();
// Load OneNote document.
Document document = new Document(dataDir + "Aspose.one", new LoadOptions { LoadHistory = true });
// Clone into new document without history.
var cloned = new Document();
cloned.AppendChildLast(document.FirstChild.Clone());
// Clone into new document with history.
cloned = new Document();
cloned.AppendChildLast(document.FirstChild.Clone(true));
Save Document in HTML Format with External Resources
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
var document = new Document(Path.Combine(dataDir, "Aspose.one"));
var options = new HtmlSaveOptions()
{
ExportCss = ResourceExportType.ExportAsStream,
ExportFonts = ResourceExportType.ExportAsStream,
ExportImages = ResourceExportType.ExportAsStream,
FontFaceTypes = FontFaceType.Ttf
};
document.Save(dataDir + "document_out.html", options);
Save Document to a Stream in HTML Format with Embedded Resources
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
var document = new Document(Path.Combine(dataDir, "Aspose.one"));
var options = new HtmlSaveOptions()
{
ExportCss = ResourceExportType.ExportEmbedded,
ExportFonts = ResourceExportType.ExportEmbedded,
ExportImages = ResourceExportType.ExportEmbedded,
FontFaceTypes = FontFaceType.Ttf
};
var r = new MemoryStream();
document.Save(r, options);
Set Text Description for an Image
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Images();
var document = new Document();
var page = new Page(document);
var image = new Image(document, dataDir + "image.jpg")
{
AlternativeTextTitle = "This is an image's title!",
AlternativeTextDescription = "And this is an image's description!"
};
page.AppendChildLast(image);
document.AppendChildLast(page);
dataDir = dataDir + "ImageAlternativeText_out.one";
document.Save(dataDir);
Get Meta Information About a Page
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Pages();
// Load the document into Aspose.Note.
Document oneFile = new Document(dataDir + "Aspose.one");
foreach (Page page in oneFile)
{
Console.WriteLine("LastModifiedTime: {0}", page.LastModifiedTime);
Console.WriteLine("CreationTime: {0}", page.CreationTime);
Console.WriteLine("Title: {0}", page.Title);
Console.WriteLine("Level: {0}", page.Level);
Console.WriteLine("Author: {0}", page.Author);
Console.WriteLine();
}
Configure PDF Page Splitting Logic
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document doc = new Document(dataDir + "Aspose.one");
var pdfSaveOptions = new PdfSaveOptions();
// Set page splitting algorithm.
// Uncomment one of the following lines based on your requirement:
// pdfSaveOptions.PageSplittingAlgorithm = new KeepPartAndCloneSolidObjectToNextPageAlgorithm(100);
pdfSaveOptions.PageSplittingAlgorithm = new KeepPartAndCloneSolidObjectToNextPageAlgorithm(400);
dataDir = dataDir + "PageSplittUsingKeepPartAndCloneSolidObjectToNextPageAlgorithm_out.pdf";
doc.Save(dataDir, pdfSaveOptions);
Save Document in PNG Format
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document oneFile = new Document(dataDir + "Aspose.one");
// Initialize ImageSaveOptions object
ImageSaveOptions opts = new ImageSaveOptions(SaveFormat.Png)
{
// Set page index.
PageIndex = 1
};
dataDir = dataDir + "ConvertSpecificPageToImage_out.png";
// Save the document as PNG.
oneFile.Save(dataDir, opts);
Edit a Page’s History
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Pages();
// Load OneNote document and get the first child.
Document document = new Document(dataDir + "Aspose.one");
Page page = document.FirstChild;
var pageHistory = document.GetPageHistory(page);
pageHistory.RemoveRange(0, 1);
pageHistory[0] = new Page(document);
if (pageHistory.Count > 1)
{
pageHistory[1].Title.TitleText.Text = "New Title";
pageHistory.Add(new Page(document));
pageHistory.Insert(1, new Page(document));
document.Save(dataDir + "ModifyPageHistory_out.one");
}
Check if Document is Password-Protected by Specific Password
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fileName = Path.Combine(dataDir, "Aspose.one");
Document document;
if (Document.IsEncrypted(fileName, "VerySecretPassword", out document))
{
if (document != null)
{
Console.WriteLine("The document is decrypted. It is loaded and ready to be processed.");
}
else
{
Console.WriteLine("The document is encrypted. Invalid password was provided.");
}
}
else
{
Console.WriteLine("The document is NOT encrypted. It is loaded and ready to be processed.");
}
Apply Dark Theme Style to a Document
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Text();
// Load the document into Aspose.Note.
Document doc = new Document(Path.Combine(dataDir, "Aspose.one"));
foreach (var page in doc)
{
page.BackgroundColor = Color.Black;
}
foreach (var node in doc.GetChildNodes<richtext>())
{
var c = node.ParagraphStyle.FontColor;
if (c.IsEmpty || Math.Abs(c.R - Color.Black.R) + Math.Abs(c.G - Color.Black.G) + Math.Abs(c.B - Color.Black.B) <= 30)
{
node.ParagraphStyle.FontColor = Color.White;
}
}
doc.Save(Path.Combine(dataDir, "AsposeDarkTheme.pdf"));
Traverse Notebook Content
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fileName = "Open Notebook.onetoc2";
try
{
var notebook = new Notebook(dataDir + fileName);
foreach (var notebookChildNode in notebook)
{
Console.WriteLine(notebookChildNode.DisplayName);
if (notebookChildNode is Document)
{
// Do something with child document
}
else if (notebookChildNode is Notebook)
{
// Do something with child notebook
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Extract an Image from a Document
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Images();
// Load the document into Aspose.Note.
Document oneFile = new Document(dataDir + "Aspose.one");
// Get all Image nodes.
IList<Aspose.Note.Image> nodes = oneFile.GetChildNodes<Aspose.Note.Image>();
foreach (Aspose.Note.Image image in nodes)
{
using (MemoryStream stream = new MemoryStream(image.Bytes))
{
using (Bitmap bitmap = new Bitmap(stream))
{
// Save image bytes to a file.
bitmap.Save(Path.Combine(dataDir, Path.GetFileName(image.FileName)));
}
}
}
Save a Document in PDF Format (Single Page)
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document oneFile = new Document(dataDir + "Aspose.one");
// Initialize PdfSaveOptions object.
PdfSaveOptions opts = new PdfSaveOptions
{
// Set page index of first page to be saved.
PageIndex = 0,
// Set page count.
PageCount = 1,
};
// Save the document as PDF.
dataDir = dataDir + "SaveRangeOfPagesAsPDF_out.pdf";
oneFile.Save(dataDir, opts);
Save a Document in PDF Format Using Specific Settings
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document doc = new Document(dataDir + "Aspose.one");
// Initialize PdfSaveOptions object.
PdfSaveOptions opts = new PdfSaveOptions
{
// Use Jpeg compression.
ImageCompression = Saving.Pdf.PdfImageCompression.Jpeg,
// Quality for JPEG compression.
JpegQuality = 90
};
dataDir = dataDir + "Document.SaveWithOptions_out.pdf";
doc.Save(dataDir, opts);
Print Document with Specified Options
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
var document = new Aspose.Note.Document(dataDir + "Aspose.one");
var printerSettings = new PrinterSettings() { FromPage = 0, ToPage = 10 };
printerSettings.DefaultPageSettings.Landscape = true;
printerSettings.DefaultPageSettings.Margins = new System.Drawing.Printing.Margins(50, 50, 150, 50);
document.Print(new PrintOptions()
{
PrinterSettings = printerSettings,
Resolution = 1200,
PageSplittingAlgorithm = new KeepSolidObjectsAlgorithm(),
DocumentName = "Test.one"
});
Get Content of an Attached File
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Attachments();
// Load the document into Aspose.Note.
Document oneFile = new Document(dataDir + "Sample1.one");
// Get a list of attached file nodes.
IList<AttachedFile> nodes = oneFile.GetChildNodes<AttachedFile>();
// Iterate through all nodes.
foreach (AttachedFile file in nodes)
{
// Load attached file into a stream object.
using (Stream outputStream = new MemoryStream(file.Bytes))
{
// Create a local file.
using (Stream fileStream = System.IO.File.OpenWrite(String.Format(dataDir + file.FileName)))
{
// Copy file stream.
CopyStream(outputStream, fileStream);
}
}
}
Get Image Meta Information
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Images();
// Load the document into Aspose.Note.
Document oneFile = new Document(dataDir + "Aspose.one");
// Get all Image nodes
IList<Aspose.Note.Image> images = oneFile.GetChildNodes<Aspose.Note.Image>();
foreach (Aspose.Note.Image image in images)
{
Console.WriteLine("Width: {0}", image.Width);
Console.WriteLine("Height: {0}", image.Height);
Console.WriteLine("OriginalWidth: {0}", image.OriginalWidth);
Console.WriteLine("OriginalHeight: {0}", image.OriginalHeight);
Console.WriteLine("FileName: {0}", image.FileName);
Console.WriteLine("LastModifiedTime: {0}", image.LastModifiedTime);
Console.WriteLine();
}
Get Page History Information
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Pages();
// Load OneNote document
Document document = new Document(dataDir + "Aspose.one", new LoadOptions { LoadHistory = true });
// Get first page
Page firstPage = document.FirstChild;
foreach (Page pageRevision in document.GetPageHistory(firstPage))
{
/* Use pageRevision like a regular page. */
Console.WriteLine("LastModifiedTime: {0}", pageRevision.LastModifiedTime);
Console.WriteLine("CreationTime: {0}", pageRevision.CreationTime);
Console.WriteLine("Title: {0}", pageRevision.Title);
Console.WriteLine("Level: {0}", pageRevision.Level);
Console.WriteLine("Author: {0}", pageRevision.Author);
Console.WriteLine();
}
Add a File to a Document Using Filepath
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Attachments();
// Create an object of the Document class.
Document doc = new Document();
// Initialize a Page class object.
Aspose.Note.Page page = new Aspose.Note.Page(doc);
// Initialize an Outline class object.
Outline outline = new Outline(doc);
// Initialize an OutlineElement class object.
OutlineElement outlineElem = new OutlineElement(doc);
// Initialize an AttachedFile class object.
AttachedFile attachedFile = new AttachedFile(doc, dataDir + "attachment.txt");
// Add the attached file.
outlineElem.AppendChildLast(attachedFile);
// Add the outline element node.
outline.AppendChildLast(outlineElem);
// Add the outline node.
page.AppendChildLast(outline);
// Add the page node.
doc.AppendChildLast(page);
dataDir = dataDir + "AttachFileByPath_out.one";
doc.Save(dataDir);
Create Document and Save to HTML Format (Default Options)
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Initialize OneNote document
Document doc = new Document();
Page page = doc.AppendChildLast(new Page());
// Default style for all text in the document.
ParagraphStyle textStyle = new ParagraphStyle
{
FontColor = Color.Black,
FontName = "Arial",
FontSize = 10
};
page.Title = new Title()
{
TitleText = new RichText()
{
Text = "Title text.",
ParagraphStyle = textStyle
},
TitleDate = new RichText()
{
Text = new DateTime(2011, 11, 11)
.ToString("D", CultureInfo.InvariantCulture),
ParagraphStyle = textStyle
},
TitleTime = new RichText()
{
Text = "12:34",
ParagraphStyle = textStyle
}
};
// Save into HTML format
dataDir = dataDir + "CreateOneNoteDocAndSaveToHTML_out.html";
doc.Save(dataDir);
Check if a Page is a Conflict Page and Fix It
string dataDir = RunExamples.GetDataDir_Pages();
// Load OneNote document
Document doc = new Document(dataDir + "Aspose.one", new LoadOptions { LoadHistory = true });
var history = doc.GetPageHistory(doc.FirstChild);
for (int i = 0; i < history.Count; i++)
{
var historyPage = history[i];
Console.Write(" {0}. Author: {1}, {2:dd.MM.yyyy hh.mm.ss}",
i,
historyPage.PageContentRevisionSummary.AuthorMostRecent,
historyPage.PageContentRevisionSummary.LastModifiedTime);
Console.WriteLine(historyPage.IsConflictPage ? ", IsConflict: true" : string.Empty);
// By default, conflict pages are just skipped on saving.
// If marked as non-conflict, they will be saved as usual in the history.
if (historyPage.IsConflictPage)
historyPage.IsConflictPage = false;
}
doc.Save(dataDir + "ConflictPageManipulation_out.one", SaveFormat.One);
Add an Image from File with Custom Properties
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Images();
// Load document from the stream.
Document doc = new Document(dataDir + "Aspose.one");
// Get the first page of the document.
Aspose.Note.Page page = doc.FirstChild;
// Load an image from the file.
Aspose.Note.Image image = new Aspose.Note.Image(doc, dataDir + "image.jpg")
{
// Change the image's size according to your needs (optional).
Width = 100,
Height = 100,
// Set the image's location in the page (optional).
HorizontalOffset = 100,
VerticalOffset = 400,
// Set image alignment.
Alignment = HorizontalAlignment.Right
};
// Add the image to the page.
page.AppendChildLast(image);
Add a File from a Stream with an Icon
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Attachments();
// Create an object of the Document class.
Document doc = new Document();
// Initialize a Page class object.
Aspose.Note.Page page = new Aspose.Note.Page(doc);
// Initialize an Outline class object.
Outline outline = new Outline(doc);
// Initialize an OutlineElement class object.
OutlineElement outlineElem = new OutlineElement(doc);
using (var stream = File.OpenRead(dataDir + "icon.jpg"))
{
// Initialize AttachedFile class object and also pass its icon path.
AttachedFile attachedFile = new AttachedFile(doc, dataDir + "attachment.txt", stream, ImageFormat.Jpeg);
// Add attached file.
outlineElem.AppendChildLast(attachedFile);
}
// Add outline element node.
outline.AppendChildLast(outlineElem);
// Add outline node.
page.AppendChildLast(outline);
// Add page node.
doc.AppendChildLast(page);
dataDir = dataDir + "AttachFileAndSetIcon_out.one";
doc.Save(dataDir);
Configure PDF Splitting Algorithms for Long OneNote Pages
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document doc = new Document(dataDir + "Aspose.one");
var pdfSaveOptions = new PdfSaveOptions();
// Set the PageSplittingAlgorithm to different algorithms as needed.
pdfSaveOptions.PageSplittingAlgorithm = new AlwaysSplitObjectsAlgorithm();
// Or:
pdfSaveOptions.PageSplittingAlgorithm = new KeepPartAndCloneSolidObjectToNextPageAlgorithm();
// Or:
pdfSaveOptions.PageSplittingAlgorithm = new KeepSolidObjectsAlgorithm();
float heightLimitOfClonedPart = 500;
pdfSaveOptions.PageSplittingAlgorithm = new KeepPartAndCloneSolidObjectToNextPageAlgorithm(heightLimitOfClonedPart);
// Or:
pdfSaveOptions.PageSplittingAlgorithm = new KeepSolidObjectsAlgorithm(heightLimitOfClonedPart);
// Alternatively, setting the algorithm with specific height limits.
pdfSaveOptions.PageSplittingAlgorithm = new KeepSolidObjectsAlgorithm(100);
// Or:
pdfSaveOptions.PageSplittingAlgorithm = new KeepSolidObjectsAlgorithm(400);
// Define the output file path.
dataDir = dataDir + "UsingKeepSOlidObjectsAlgorithm_out.pdf";
doc.Save(dataDir);
Create a Document and Save a Specified Range of Pages in HTML Format
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Initialize OneNote document
Document doc = new Document();
Page page = doc.AppendChildLast(new Page());
// Default style for all text in the document.
ParagraphStyle textStyle = new ParagraphStyle
{
FontColor = Color.Black,
FontName = "Arial",
FontSize = 10
};
page.Title = new Title()
{
TitleText = new RichText()
{
Text = "Title text.",
ParagraphStyle = textStyle
},
TitleDate = new RichText()
{
Text = new DateTime(2011, 11, 11)
.ToString("D", CultureInfo.InvariantCulture),
ParagraphStyle = textStyle
},
TitleTime = new RichText()
{
Text = "12:34",
ParagraphStyle = textStyle
}
};
// Save into HTML format
dataDir = dataDir + "CreateAndSavePageRange_out.html";
doc.Save(dataDir, new HtmlSaveOptions
{
PageCount = 1,
PageIndex = 0
});
Create a Document with a Titled Page
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Create an object of the Document class.
Document doc = new Aspose.Note.Document();
// Initialize Page class object.
Aspose.Note.Page page = new Aspose.Note.Page(doc);
// Default style for all text in the document.
ParagraphStyle textStyle = new ParagraphStyle
{
FontColor = Color.Black,
FontName = "Arial",
FontSize = 10
};
// Set page title properties.
page.Title = new Title(doc)
{
TitleText = new RichText(doc) { Text = "Title text.", ParagraphStyle = textStyle },
TitleDate = new RichText(doc) { Text = new DateTime(2011, 11, 11).ToString("D", CultureInfo.InvariantCulture), ParagraphStyle = textStyle },
TitleTime = new RichText(doc) { Text = "12:34", ParagraphStyle = textStyle }
};
// Append Page node in the document.
doc.AppendChildLast(page);
// Save OneNote document.
dataDir = dataDir + "CreateDocWithPageTitle_out.one";
doc.Save(dataDir);
Add an Image from Stream to a Document
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Images();
// Create an object of the Document class.
Document doc = new Document();
// Initialize Page class object.
Aspose.Note.Page page = new Aspose.Note.Page(doc);
Outline outline1 = new Outline(doc);
OutlineElement outlineElem1 = new OutlineElement(doc);
using (FileStream fs = File.OpenRead(dataDir + "image.jpg"))
{
// Load the image using the image name, extension, and stream.
Aspose.Note.Image image1 = new Aspose.Note.Image(doc, "Penguins.jpg", fs)
{
// Set image alignment.
Alignment = HorizontalAlignment.Right
};
outlineElem1.AppendChildLast(image1);
}
outline1.AppendChildLast(outlineElem1);
page.AppendChildLast(outline1);
doc.AppendChildLast(page);
// Save OneNote document.
dataDir = dataDir + "BuildDocAndInsertImageUsingImageStream_out.one";
doc.Save(dataDir);
Add an Image from File to a Document
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Images();
// Create an object of the Document class.
Document doc = new Document();
// Initialize Page class object.
Aspose.Note.Page page = new Aspose.Note.Page(doc);
// Initialize Outline class object and set offset properties.
Outline outline = new Outline(doc);
// Initialize OutlineElement class object.
OutlineElement outlineElem = new OutlineElement(doc);
// Load an image by the file path.
Aspose.Note.Image image = new Aspose.Note.Image(doc, dataDir + "image.jpg")
{
// Set image alignment.
Alignment = HorizontalAlignment.Right
};
// Add image.
outlineElem.AppendChildLast(image);
// Add outline elements.
outline.AppendChildLast(outlineElem);
// Add Outline node.
page.AppendChildLast(outline);
// Add Page node.
doc.AppendChildLast(page);
// Save OneNote document.
dataDir = dataDir + "BuildDocAndInsertImage_out.one";
doc.Save(dataDir);
Create a Document with Simple Text
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Create an object of the Document class.
Document doc = new Document();
// Initialize Page class object.
Page page = new Page(doc);
// Initialize Outline class object.
Outline outline = new Outline(doc);
// Initialize OutlineElement class object.
OutlineElement outlineElem = new OutlineElement(doc);
// Initialize TextStyle class object and set formatting properties.
ParagraphStyle textStyle = new ParagraphStyle { FontColor = Color.Black, FontName = "Arial", FontSize = 10 };
// Initialize RichText class object and apply text style.
RichText text = new RichText(doc) { Text = "Hello OneNote text!", ParagraphStyle = textStyle };
// Add RichText node.
outlineElem.AppendChildLast(text);
// Add OutlineElement node.
outline.AppendChildLast(outlineElem);
// Add Outline node.
page.AppendChildLast(outline);
// Add Page node.
doc.AppendChildLast(page);
// Save OneNote document.
dataDir = dataDir + "CreateDocWithSimpleRichText_out.one";
doc.Save(dataDir);
Save a Document in Multiple Formats
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Initialize the new Document.
Document doc = new Document() { AutomaticLayoutChangesDetectionEnabled = false };
// Initialize the new Page.
Aspose.Note.Page page = new Aspose.Note.Page(doc);
// Default style for all text in the document.
ParagraphStyle textStyle = new ParagraphStyle { FontColor = Color.Black, FontName = "Arial", FontSize = 10 };
page.Title = new Title(doc)
{
TitleText = new RichText(doc) { Text = "Title text.", ParagraphStyle = textStyle },
TitleDate = new RichText(doc) { Text = new DateTime(2011, 11, 11).ToString("D", CultureInfo.InvariantCulture), ParagraphStyle = textStyle },
TitleTime = new RichText(doc) { Text = "12:34", ParagraphStyle = textStyle }
};
// Append page node.
doc.AppendChildLast(page);
// Save OneNote document in different formats.
// Export as HTML.
doc.Save(dataDir + "ConsequentExportOperations_out.html");
// Export as PDF.
doc.Save(dataDir + "ConsequentExportOperations_out.pdf");
// Export as JPG.
doc.Save(dataDir + "ConsequentExportOperations_out.jpg");
// Modify text font size.
textStyle.FontSize = 11;
// Detect layout changes manually.
doc.DetectLayoutChanges();
// Export as BMP.
doc.Save(dataDir + "ConsequentExportOperations_out.bmp");
Save Document in HTML Format with User-Defined Callbacks
// The code below creates 'documentFolder' folder containing document.html, 'css' folder with 'style.css' file,
// 'images' folder with images and 'fonts' folder with fonts.
// 'style.css' file will contain at the end the following string "/* This line is appended to stream manually by user */"
var savingCallbacks = new UserSavingCallbacks()
{
RootFolder = "documentFolder",
CssFolder = "css",
KeepCssStreamOpened = true,
ImagesFolder = "images",
FontsFolder = "fonts"
};
var options = new HtmlSaveOptions
{
FontFaceTypes = FontFaceType.Ttf,
CssSavingCallback = savingCallbacks,
FontSavingCallback = savingCallbacks,
ImageSavingCallback = savingCallbacks
};
if (!Directory.Exists(savingCallbacks.RootFolder))
{
Directory.CreateDirectory(savingCallbacks.RootFolder);
}
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
var document = new Document(Path.Combine(dataDir, "Aspose.one"));
using (var stream = File.Create(Path.Combine(savingCallbacks.RootFolder, "document.html")))
{
document.Save(stream, options);
}
using (var writer = new StreamWriter(savingCallbacks.CssStream))
{
writer.WriteLine();
writer.WriteLine("/* This line is appended to stream manually by user */");
}
Bind a Hyperlink to Text in a Document
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Tasks();
// Create an object of the Document class.
Document doc = new Document();
// Create the title text.
RichText titleText = new RichText() { ParagraphStyle = ParagraphStyle.Default }
.Append("Title!");
// Create an outline with specific size and offsets.
Outline outline = new Outline()
{
MaxWidth = 200,
MaxHeight = 200,
VerticalOffset = 100,
HorizontalOffset = 100
};
// Define text styles.
TextStyle textStyleRed = new TextStyle
{
FontColor = Color.Red,
FontName = "Arial",
FontSize = 10,
};
TextStyle textStyleHyperlink = new TextStyle
{
IsHyperlink = true,
HyperlinkAddress = "www.google.com"
};
// Create a rich text object and append styled texts.
RichText text = new RichText() { ParagraphStyle = ParagraphStyle.Default }
.Append("This is ", textStyleRed)
.Append("hyperlink", textStyleHyperlink)
.Append(". This text is not a hyperlink.", TextStyle.Default);
// Create an outline element and add the text.
OutlineElement outlineElem = new OutlineElement();
outlineElem.AppendChildLast(text);
// Add the outline element to the outline.
outline.AppendChildLast(outlineElem);
// Create a title using the title text.
Title title = new Title() { TitleText = titleText };
// Create a page with the title.
Page page = new Page() { Title = title };
// Add the outline to the page.
page.AppendChildLast(outline);
// Add the page to the document.
doc.AppendChildLast(page);
// Save the OneNote document.
dataDir = dataDir + "AddHyperlink_out.one";
doc.Save(dataDir);
Access Document Content Using Visitor Pattern
public static void Run()
{
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Open the document we want to convert.
Document doc = new Document(dataDir + "Aspose.one");
// Create an object that inherits from the DocumentVisitor class.
MyOneNoteToTxtWriter myConverter = new MyOneNoteToTxtWriter();
// This is the well known Visitor pattern. Get the model to accept a visitor.
// The model will iterate through itself by calling the corresponding methods
// on the visitor object (this is called visiting).
//
// Note that every node in the object model has the Accept method so the visiting
// can be executed not only for the whole document, but for any node in the document.
doc.Accept(myConverter);
// Once the visiting is complete, we can retrieve the result of the operation,
// that in this example, has accumulated in the visitor.
Console.WriteLine(myConverter.GetText());
Console.WriteLine(myConverter.NodeCount);
}
/// <summary>
/// Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
/// </summary>
public class MyOneNoteToTxtWriter : DocumentVisitor
{
private readonly StringBuilder mBuilder;
private bool mIsSkipText;
private int nodecount;
public MyOneNoteToTxtWriter()
{
nodecount = 0;
mIsSkipText = false;
mBuilder = new StringBuilder();
}
/// <summary>
/// Gets the plain text of the document that was accumulated by the visitor.
/// </summary>
public string GetText()
{
return mBuilder.ToString();
}
/// <summary>
/// Adds text to the current output. Honors the enabled/disabled output flag.
/// </summary>
private void AppendText(string text)
{
if (!mIsSkipText)
{
mBuilder.AppendLine(text);
}
}
/// <summary>
/// Called when a RichText node is encountered in the document.
/// </summary>
public override void VisitRichTextStart(RichText run)
{
++nodecount;
AppendText(run.Text);
}
/// <summary>
/// Called when a Document node is encountered in the document.
/// </summary>
public override void VisitDocumentStart(Document document)
{
++nodecount;
}
/// <summary>
/// Called when a Page node is encountered in the document.
/// </summary>
public override void VisitPageStart(Page page)
{
++nodecount;
AppendText($"*** Page '{page.Title?.TitleText?.Text ?? "(no title)"}' ***");
}
/// <summary>
/// Called when processing of a Page node is finished.
/// </summary>
public override void VisitPageEnd(Page page)
{
AppendText(string.Empty);
}
/// <summary>
/// Called when a Title node is encountered in the document.
/// </summary>
public override void VisitTitleStart(Title title)
{
++nodecount;
}
/// <summary>
/// Called when an Image node is encountered in the document.
/// </summary>
public override void VisitImageStart(Image image)
{
++nodecount;
}
/// <summary>
/// Called when an OutlineGroup node is encountered in the document.
/// </summary>
public override void VisitOutlineGroupStart(OutlineGroup outlineGroup)
{
++nodecount;
}
/// <summary>
/// Called when an Outline node is encountered in the document.
/// </summary>
public override void VisitOutlineStart(Outline outline)
{
++nodecount;
}
/// <summary>
/// Called when an OutlineElement node is encountered in the document.
/// </summary>
public override void VisitOutlineElementStart(OutlineElement outlineElement)
{
++nodecount;
}
/// <summary>
/// Gets the total count of nodes visited.
/// </summary>
public int NodeCount
{
get { return nodecount; }
}
}
Constructors
Default Document Constructor
public Document()
Open Document from File Constructor
public Document(string filePath)
Parameters
filePath
string
The file path.
Exceptions
UnsupportedFileFormatException
FileCorruptedException
IncorrectPasswordException
InvalidOperationException
IOException
Open Document from File with Load Options Constructor
public Document(string filePath, LoadOptions loadOptions)
Parameters
filePath
stringloadOptions
LoadOptions
Exceptions
UnsupportedFileFormatException
FileCorruptedException
IncorrectPasswordException
InvalidOperationException
IOException
Open Document from Stream Constructor
public Document(Stream inStream)
Parameters
inStream
Stream
Exceptions
UnsupportedFileFormatException
FileCorruptedException
IncorrectPasswordException
InvalidOperationException
IOException
ArgumentException
Open Document from Stream with Load Options Constructor
public Document(Stream inStream, LoadOptions loadOptions)
Parameters
inStream
StreamloadOptions
LoadOptions
Exceptions
UnsupportedFileFormatException
FileCorruptedException
IncorrectPasswordException
InvalidOperationException
IOException
ArgumentException
Properties
«««< Updated upstream
Automatic Layout Changes Detection Property
=======
### <a id="Aspose_Note_Document_AutomaticLayoutChangesDetectionEnabled"></a> AutomaticLayoutChangesDetectionEnabled
Gets or sets a value indicating whether Aspose.Note performs detection of layout changes automatically.
Default value is `true`.
```csharp
>>>>>>> Stashed changes
public bool AutomaticLayoutChangesDetectionEnabled { get; set; }
Property Value
Examples
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Initialize the new Document.
Document doc = new Document() { AutomaticLayoutChangesDetectionEnabled = false };
// Initialize the new Page.
Aspose.Note.Page page = new Aspose.Note.Page(doc);
// Default style for all text in the document.
ParagraphStyle textStyle = new ParagraphStyle { FontColor = Color.Black, FontName = "Arial", FontSize = 10 };
page.Title = new Title(doc)
{
TitleText = new RichText(doc) { Text = "Title text.", ParagraphStyle = textStyle },
TitleDate = new RichText(doc) { Text = new DateTime(2011, 11, 11).ToString("D", CultureInfo.InvariantCulture), ParagraphStyle = textStyle },
TitleTime = new RichText(doc) { Text = "12:34", ParagraphStyle = textStyle }
};
// Append page node.
doc.AppendChildLast(page);
// Save OneNote document in different formats.
// Save as HTML.
doc.Save(dataDir + "ConsequentExportOperations_out.html");
// Save as PDF.
doc.Save(dataDir + "ConsequentExportOperations_out.pdf");
// Save as JPG.
doc.Save(dataDir + "ConsequentExportOperations_out.jpg");
// Modify text font size.
textStyle.FontSize = 11;
// Detect layout changes manually.
doc.DetectLayoutChanges();
// Save as BMP.
doc.Save(dataDir + "ConsequentExportOperations_out.bmp");
Color Property
public Color Color { get; set; }
Property Value
Creation Time Property
public DateTime CreationTime { get; set; }
Property Value
Display Name Property
public string DisplayName { get; set; }
Property Value
File Format Property
public FileFormat FileFormat { get; }
Property Value
Examples
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
var document = new Aspose.Note.Document(dataDir + "Aspose.one");
switch (document.FileFormat)
{
case FileFormat.OneNote2010:
// Process OneNote 2010.
break;
case FileFormat.OneNoteOnline:
// Process OneNote Online.
break;
}
Globally Unique Identifier Property
public Guid Guid { get; }
Property Value
Methods
Accept Document Visitor Method
public override void Accept(DocumentVisitor visitor)
Parameters
visitor
DocumentVisitor
The object of a class derived from the Aspose.Note.DocumentVisitor.
Examples
public static void Run()
{
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Open the document we want to convert.
Document doc = new Document(dataDir + "Aspose.one");
// Create an object that inherits from the DocumentVisitor class.
MyOneNoteToTxtWriter myConverter = new MyOneNoteToTxtWriter();
// This is the well known Visitor pattern. Get the model to accept a visitor.
// The model will iterate through itself by calling the corresponding methods
// on the visitor object (this is called visiting).
//
// Note that every node in the object model has the Accept method so the visiting
// can be executed not only for the whole document, but for any node in the document.
doc.Accept(myConverter);
// Once the visiting is complete, we can retrieve the result of the operation,
// that in this example, has accumulated in the visitor.
Console.WriteLine(myConverter.GetText());
Console.WriteLine(myConverter.NodeCount);
}
/// <summary>
/// Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
/// </summary>
public class MyOneNoteToTxtWriter : DocumentVisitor
{
private readonly StringBuilder mBuilder;
private bool mIsSkipText;
private int nodecount;
public MyOneNoteToTxtWriter()
{
nodecount = 0;
mIsSkipText = false;
mBuilder = new StringBuilder();
}
/// <summary>
/// Gets the plain text of the document that was accumulated by the visitor.
/// </summary>
public string GetText()
{
return mBuilder.ToString();
}
/// <summary>
/// Adds text to the current output. Honors the enabled/disabled output flag.
/// </summary>
private void AppendText(string text)
{
if (!mIsSkipText)
{
mBuilder.AppendLine(text);
}
}
/// <summary>
/// Called when a RichText node is encountered in the document.
/// </summary>
public override void VisitRichTextStart(RichText run)
{
++nodecount;
AppendText(run.Text);
}
/// <summary>
/// Called when a Document node is encountered in the document.
/// </summary>
public override void VisitDocumentStart(Document document)
{
++nodecount;
}
/// <summary>
/// Called when a Page node is encountered in the document.
/// </summary>
public override void VisitPageStart(Page page)
{
++nodecount;
AppendText($"*** Page '{page.Title?.TitleText?.Text ?? "(no title)"}' ***");
}
/// <summary>
/// Called when processing of a Page node is finished.
/// </summary>
public override void VisitPageEnd(Page page)
{
AppendText(string.Empty);
}
/// <summary>
/// Called when a Title node is encountered in the document.
/// </summary>
public override void VisitTitleStart(Title title)
{
++nodecount;
}
/// <summary>
/// Called when an Image node is encountered in the document.
/// </summary>
public override void VisitImageStart(Image image)
{
++nodecount;
}
/// <summary>
/// Called when an OutlineGroup node is encountered in the document.
/// </summary>
public override void VisitOutlineGroupStart(OutlineGroup outlineGroup)
{
++nodecount;
}
/// <summary>
/// Called when an Outline node is encountered in the document.
/// </summary>
public override void VisitOutlineStart(Outline outline)
{
++nodecount;
}
/// <summary>
/// Called when an OutlineElement node is encountered in the document.
/// </summary>
public override void VisitOutlineElementStart(OutlineElement outlineElement)
{
++nodecount;
}
/// <summary>
/// Gets the total count of nodes visited by the Visitor.
/// </summary>
public int NodeCount
{
get { return nodecount; }
}
}
Detect Layout Changes Method
public void DetectLayoutChanges()
Examples
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Initialize the new Document.
Document doc = new Document() { AutomaticLayoutChangesDetectionEnabled = false };
// Initialize the new Page.
Aspose.Note.Page page = new Aspose.Note.Page(doc);
// Default style for all text in the document.
ParagraphStyle textStyle = new ParagraphStyle { FontColor = Color.Black, FontName = "Arial", FontSize = 10 };
page.Title = new Title(doc)
{
TitleText = new RichText(doc) { Text = "Title text.", ParagraphStyle = textStyle },
TitleDate = new RichText(doc) { Text = new DateTime(2011, 11, 11).ToString("D", CultureInfo.InvariantCulture), ParagraphStyle = textStyle },
TitleTime = new RichText(doc) { Text = "12:34", ParagraphStyle = textStyle }
};
// Append page node.
doc.AppendChildLast(page);
// Save OneNote document in different formats.
// Save as HTML.
doc.Save(dataDir + "ConsequentExportOperations_out.html");
// Save as PDF.
doc.Save(dataDir + "ConsequentExportOperations_out.pdf");
// Save as JPG.
doc.Save(dataDir + "ConsequentExportOperations_out.jpg");
// Modify text style.
textStyle.FontSize = 11;
// Detect layout changes manually.
doc.DetectLayoutChanges();
// Save as BMP.
doc.Save(dataDir + "ConsequentExportOperations_out.bmp");
Get Page History of a Page
public PageHistory GetPageHistory(Page page)
Parameters
page
Page – The current revision of a page.
Returns
PageHistory – The Aspose.Note.PageHistory.
Examples
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Pages();
// Load OneNote document and get first child.
Document document = new Document(dataDir + "Aspose.one");
Page page = document.FirstChild;
Page previousPageVersion = document.GetPageHistory(page).Last();
document.RemoveChild(page);
document.AppendChildLast(previousPageVersion);
document.Save(dataDir + "RollBackRevisions_out.one");
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Pages();
// Load OneNote document and get first child.
Document document = new Document(dataDir + "Aspose.one");
Page page = document.FirstChild;
var pageHistory = document.GetPageHistory(page);
pageHistory.RemoveRange(0, 1);
pageHistory[0] = new Page(document);
if (pageHistory.Count > 1)
{
pageHistory[1].Title.TitleText.Text = "New Title";
pageHistory.Add(new Page(document));
pageHistory.Insert(1, new Page(document));
document.Save(dataDir + "ModifyPageHistory_out.one");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Pages();
// Load OneNote document.
Document doc = new Document(dataDir + "Aspose.one", new LoadOptions { LoadHistory = true });
var history = doc.GetPageHistory(doc.FirstChild);
for (int i = 0; i < history.Count; i++)
{
var historyPage = history[i];
Console.Write(" {0}. Author: {1}, {2:dd.MM.yyyy hh.mm.ss}",
i,
historyPage.PageContentRevisionSummary.AuthorMostRecent,
historyPage.PageContentRevisionSummary.LastModifiedTime);
Console.WriteLine(historyPage.IsConflictPage ? ", IsConflict: true" : string.Empty);
// By default conflict pages are just skipped on saving.
// If marked as non-conflict then it will be saved as a usual page in the history.
if (historyPage.IsConflictPage)
historyPage.IsConflictPage = false;
}
doc.Save(dataDir + "ConflictPageManipulation_out.one", SaveFormat.One);
Import PDF Document Pages into OneNote
public Document Import(Stream stream, PdfImportOptions importOptions = null, MergeOptions mergeOptions = null)
Parameters
stream
Stream – A stream with PDF document.importOptions
PdfImportOptions – Specifies the options how to import pages from PDF document.mergeOptions
MergeOptions – Specifies the options how to merge provided pages.
Returns
Document – Returns the reference to the document.
Import PDF Document from File into OneNote
public Document Import(string file, PdfImportOptions importOptions = null, MergeOptions mergeOptions = null)
Parameters
file
string – A file with PDF document.importOptions
PdfImportOptionsmergeOptions
MergeOptions
Returns
Examples
string dataDir = RunExamples.GetDataDir_Import();
var d = new Document();
d.Import(Path.Combine(dataDir, "sampleText.pdf"))
.Import(Path.Combine(dataDir, "sampleImage.pdf"))
.Import(Path.Combine(dataDir, "sampleTable.pdf"));
d.Save(Path.Combine(dataDir, "sample_SimpleMerge.one"));
string dataDir = RunExamples.GetDataDir_Import();
var d = new Document();
foreach (var file in new[] { "sampleText.pdf", "sampleImage.pdf", "sampleTable.pdf" })
{
d.AppendChildLast(new Page())
.Title = new Title()
{
TitleText = new RichText() { ParagraphStyle = ParagraphStyle.Default }.Append(file)
};
d.Import(
Path.Combine(dataDir, file),
new PdfImportOptions(),
new MergeOptions() { InsertAt = int.MaxValue, InsertAsChild = true });
}
d.Save(Path.Combine(dataDir, "sample_StructuredMerge.one"));
string dataDir = RunExamples.GetDataDir_Import();
var d = new Document();
var importOptions = new PdfImportOptions();
var mergeOptions = new MergeOptions() { ImportAsSinglePage = true, PageSpacing = 100 };
d.Import(Path.Combine(dataDir, "sampleText.pdf"), importOptions, mergeOptions)
.Import(Path.Combine(dataDir, "sampleImage.pdf"), importOptions, mergeOptions)
.Import(Path.Combine(dataDir, "sampleTable.pdf"), importOptions, mergeOptions);
d.Save(Path.Combine(dataDir, "sample_SinglePageMerge.one"));
Import HTML Document Pages into OneNote (Stream)
public Document Import(Stream stream, HtmlImportOptions importOptions, MergeOptions mergeOptions = null)
Import HTML Document Pages into OneNote (File)
public Document Import(string file, HtmlImportOptions importOptions, MergeOptions mergeOptions = null)
Check if a Stream Document is Encrypted with LoadOptions
public static bool IsEncrypted(Stream stream, LoadOptions options, out Document document)
Parameters
stream
Streamoptions
LoadOptionsdocument
Document
Returns
Examples
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fileName = Path.Combine(dataDir, "Aspose.one");
Document document;
if (!Document.IsEncrypted(fileName, out document))
{
Console.WriteLine("The document is loaded and ready to be processed.");
}
else
{
Console.WriteLine("The document is encrypted. Provide a password.");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fileName = Path.Combine(dataDir, "Aspose.one");
Document document;
if (Document.IsEncrypted(fileName, "VerySecretPassword", out document))
{
if (document != null)
{
Console.WriteLine("The document is decrypted. It is loaded and ready to be processed.");
}
else
{
Console.WriteLine("The document is encrypted. Invalid password was provided.");
}
}
else
{
Console.WriteLine("The document is NOT encrypted. It is loaded and ready to be processed.");
}
Check if a Stream Document is Encrypted with Password
public static bool IsEncrypted(Stream stream, string password, out Document document)
Parameters
stream
Streampassword
stringdocument
Document
Returns
Examples
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fileName = Path.Combine(dataDir, "Aspose.one");
Document document;
if (!Document.IsEncrypted(fileName, out document))
{
Console.WriteLine("The document is loaded and ready to be processed.");
}
else
{
Console.WriteLine("The document is encrypted. Provide a password.");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fileName = Path.Combine(dataDir, "Aspose.one");
Document document;
if (Document.IsEncrypted(fileName, "VerySecretPassword", out document))
{
if (document != null)
{
Console.WriteLine("The document is decrypted. It is loaded and ready to be processed.");
}
else
{
Console.WriteLine("The document is encrypted. Invalid password was provided.");
}
}
else
{
Console.WriteLine("The document is NOT encrypted. It is loaded and ready to be processed.");
}
Check if a Document from Stream is Encrypted (No Password)
public static bool IsEncrypted(Stream stream, out Document document)
Parameters
stream
Streamdocument
Document
Returns
Examples
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fileName = Path.Combine(dataDir, "Aspose.one");
Document document;
if (!Document.IsEncrypted(fileName, out document))
{
Console.WriteLine("The document is loaded and ready to be processed.");
}
else
{
Console.WriteLine("The document is encrypted. Provide a password.");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fileName = Path.Combine(dataDir, "Aspose.one");
Document document;
if (Document.IsEncrypted(fileName, "VerySecretPassword", out document))
{
if (document != null)
{
Console.WriteLine("The document is decrypted. It is loaded and ready to be processed.");
}
else
{
Console.WriteLine("The document is encrypted. Invalid password was provided.");
}
}
else
{
Console.WriteLine("The document is NOT encrypted. It is loaded and ready to be processed.");
}
Check if a Document from File is Encrypted with LoadOptions
public static bool IsEncrypted(string filePath, LoadOptions options, out Document document)
Parameters
filePath
stringoptions
LoadOptionsdocument
Document
Returns
Examples
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fileName = Path.Combine(dataDir, "Aspose.one");
Document document;
if (!Document.IsEncrypted(fileName, out document))
{
Console.WriteLine("The document is loaded and ready to be processed.");
}
else
{
Console.WriteLine("The document is encrypted. Provide a password.");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fileName = Path.Combine(dataDir, "Aspose.one");
Document document;
if (Document.IsEncrypted(fileName, "VerySecretPassword", out document))
{
if (document != null)
{
Console.WriteLine("The document is decrypted. It is loaded and ready to be processed.");
}
else
{
Console.WriteLine("The document is encrypted. Invalid password was provided.");
}
}
else
{
Console.WriteLine("The document is NOT encrypted. It is loaded and ready to be processed.");
}
Check if a Document from File is Encrypted (No Password)
public static bool IsEncrypted(string filePath, out Document document)
Parameters
filePath
stringdocument
Document
Returns
Examples
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fileName = Path.Combine(dataDir, "Aspose.one");
Document document;
// Check if the document is NOT password-protected.
// If the document is not encrypted, it is loaded and ready to be processed.
if (!Document.IsEncrypted(fileName, out document))
{
Console.WriteLine("The document is loaded and ready to be processed.");
}
else
{
Console.WriteLine("The document is encrypted. Provide a password.");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fileName = Path.Combine(dataDir, "Aspose.one");
Document document;
// Check if the document is encrypted using a specific password.
if (Document.IsEncrypted(fileName, "VerySecretPassword", out document))
{
if (document != null)
{
Console.WriteLine("The document is decrypted. It is loaded and ready to be processed.");
}
else
{
Console.WriteLine("The document is encrypted. Invalid password was provided.");
}
}
else
{
Console.WriteLine("The document is NOT encrypted. It is loaded and ready to be processed.");
}
Check if a Document from File is Encrypted with Password
public static bool IsEncrypted(string filePath, string password, out Document document)
Parameters
filePath
stringpassword
stringdocument
Document
Returns
Examples
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fileName = Path.Combine(dataDir, "Aspose.one");
Document document;
if (!Document.IsEncrypted(fileName, out document))
{
Console.WriteLine("The document is loaded and ready to be processed.");
}
else
{
Console.WriteLine("The document is encrypted. Provide a password.");
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fileName = Path.Combine(dataDir, "Aspose.one");
Document document;
if (Document.IsEncrypted(fileName, "VerySecretPassword", out document))
{
if (document != null)
{
Console.WriteLine("The document is decrypted. It is loaded and ready to be processed.");
}
else
{
Console.WriteLine("The document is encrypted. Invalid password was provided.");
}
}
else
{
Console.WriteLine("The document is NOT encrypted. It is loaded and ready to be processed.");
}
Merge Pages into a Document
public Document Merge(IEnumerable<page> pages, MergeOptions mergeOptions = null)
Parameters
pages
IEnumerable<Page> – A set of pages.mergeOptions
MergeOptions – Specifies the options how to merge provided pages.
Returns
Examples
// Merge PDF pages into a OneNote document using custom merge options.
string dataDir = RunExamples.GetDataDir_Import();
var d = new Document();
var mergeOptions = new MergeOptions() { ImportAsSinglePage = true, PageSpacing = 100 };
IEnumerable<Page> pages = PdfImporter.Import(Path.Combine(dataDir, "SampleGrouping.pdf"));
while (pages.Any())
{
d.Merge(pages.Take(5), mergeOptions);
pages = pages.Skip(5);
}
d.Save(Path.Combine(dataDir, "sample_CustomMerge.one"));
/*
* To print the document using the default printer, simply call:
*
* d.Print();
*/
public void Print()
{
// This method prints the document using the default printer.
}
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
var document = new Aspose.Note.Document(dataDir + "Aspose.one");
document.Print();
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
var document = new Aspose.Note.Document(dataDir + "Aspose.one");
var printerSettings = new PrinterSettings() { FromPage = 0, ToPage = 10 };
printerSettings.DefaultPageSettings.Landscape = true;
printerSettings.DefaultPageSettings.Margins = new System.Drawing.Printing.Margins(50, 50, 150, 50);
document.Print(new PrintOptions()
{
PrinterSettings = printerSettings,
Resolution = 1200,
PageSplittingAlgorithm = new KeepSolidObjectsAlgorithm(),
DocumentName = "Test.one"
});
Print Document Using Specified Print Options
public void Print(PrintOptions options)
Parameters
options
PrintOptions
Options used to print a document. Can be null.
Save Document to File
public void Save(string fileName)
Parameters
fileName
string – The full name for the file. If a file with the specified full name already exists, the existing file is overwritten.
Examples
string inputFile = "Sample1.one";
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string outputFile = "SaveDocToOneNoteFormat_out.one";
Document doc = new Document(dataDir + inputFile);
doc.Save(dataDir + outputFile);
Exceptions
IncorrectDocumentStructureException
UnsupportedSaveFormatException
Save Document to Stream
public void Save(Stream stream)
Parameters
stream
Stream – The System.IO.Stream where the document will be saved.
Exceptions
IncorrectDocumentStructureException
UnsupportedSaveFormatException
Save Document to File with SaveFormat
public void Save(string fileName, SaveFormat format)
Parameters
fileName
string – The full name for the file.format
SaveFormat – The format in which to save the document.
Examples
string inputFile = "Sample1.one";
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string outputFile = "SaveDocToOneNoteFormatUsingSaveFormat_out.one";
Document document = new Document(dataDir + inputFile);
document.Save(dataDir + outputFile, SaveFormat.One);
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document oneFile = new Document(dataDir + "Aspose.one");
dataDir = dataDir + "SaveToImageDefaultOptions_out.gif";
// Save the document as gif.
oneFile.Save(dataDir, SaveFormat.Gif);
Exceptions
IncorrectDocumentStructureException
UnsupportedSaveFormatException
Save Document to Stream with SaveFormat
public void Save(Stream stream, SaveFormat format)
Parameters
stream
Streamformat
SaveFormat
Examples
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document oneFile = new Document(dataDir + "Aspose.one");
// Save the document as PDF.
dataDir = dataDir + "SaveWithDefaultSettings_out.pdf";
oneFile.Save(dataDir, SaveFormat.Pdf);
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document doc = new Document(dataDir + "Aspose.one");
MemoryStream dstStream = new MemoryStream();
doc.Save(dstStream, SaveFormat.Pdf);
// Rewind the stream position back to zero so it is ready for the next reader.
dstStream.Seek(0, SeekOrigin.Begin);
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_Text();
// Load the document into Aspose.Note.
Document doc = new Document(Path.Combine(dataDir, "Aspose.one"));
foreach (var page in doc)
{
page.BackgroundColor = Color.Black;
}
foreach (var node in doc.GetChildNodes<RichText>())
{
var c = node.ParagraphStyle.FontColor;
if (c.IsEmpty || Math.Abs(c.R - Color.Black.R) + Math.Abs(c.G - Color.Black.G) + Math.Abs(c.B - Color.Black.B) <= 30)
{
node.ParagraphStyle.FontColor = Color.White;
}
}
doc.Save(Path.Combine(dataDir, "AsposeDarkTheme.pdf"));
Exceptions
IncorrectDocumentStructureException
UnsupportedSaveFormatException
Save Document to File Using SaveOptions
public void Save(string fileName, SaveOptions options)
Parameters
fileName
stringoptions
SaveOptions
Examples
string inputFile = "Sample1.one";
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string outputFile = "SaveDocToOneNoteFormatUsingOneSaveOptions_out.one";
Document document = new Document(dataDir + inputFile);
document.Save(dataDir + outputFile, new OneSaveOptions());
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document oneFile = new Document(dataDir + "Aspose.one");
dataDir = dataDir + "SaveToJpegImageUsingSaveFormat_out.jpg";
// Save the document.
oneFile.Save(dataDir, SaveFormat.Jpeg);
// Shows how to save a document in Pdf format with Letter page layout.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document oneFile = new Document(dataDir + "OneNote.one");
var dst = Path.Combine(dataDir, "SaveToPdfUsingLetterPageSettings.pdf");
// Save the document.
oneFile.Save(dst, new PdfSaveOptions() { PageSettings = PageSettings.Letter });
// Shows how to save a document in Pdf format with A4 page layout without height limit.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document oneFile = new Document(dataDir + "OneNote.one");
var dst = Path.Combine(dataDir, "SaveToPdfUsingA4PageSettingsWithoutHeightLimit.pdf");
// Save the document.
oneFile.Save(dst, new PdfSaveOptions() { PageSettings = PageSettings.A4NoHeightLimit });
// Shows how to save a document as grayscale image.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document oneFile = new Document(dataDir + "Aspose.one");
dataDir = dataDir + "SaveAsGrayscaleImage_out.png";
// Save the document as gif.
oneFile.Save(dataDir, new ImageSaveOptions(SaveFormat.Png)
{
ColorMode = ColorMode.GrayScale
});
// Shows how to save a document as image in Tiff format using PackBits compression.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document oneFile = new Document(Path.Combine(dataDir, "Aspose.one"));
var dst = Path.Combine(dataDir, "SaveToTiffUsingPackBitsCompression.tiff");
// Save the document.
oneFile.Save(dst, new ImageSaveOptions(SaveFormat.Tiff)
{
TiffCompression = TiffCompression.PackBits
});
// Shows how to save a document as image in Tiff format using Jpeg compression.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document oneFile = new Document(Path.Combine(dataDir, "Aspose.one"));
var dst = Path.Combine(dataDir, "SaveToTiffUsingJpegCompression.tiff");
// Save the document.
oneFile.Save(dst, new ImageSaveOptions(SaveFormat.Tiff)
{
TiffCompression = TiffCompression.Jpeg,
Quality = 93
});
// Shows how to save a document as image in Tiff format using CCITT Group 3 fax compression.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document oneFile = new Document(Path.Combine(dataDir, "Aspose.one"));
var dst = Path.Combine(dataDir, "SaveToTiffUsingCcitt3Compression.tiff");
// Save the document.
oneFile.Save(dst, new ImageSaveOptions(SaveFormat.Tiff)
{
ColorMode = ColorMode.BlackAndWhite,
TiffCompression = TiffCompression.Ccitt3
});
// Shows how to save a document in pdf format.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document oneFile = new Document(dataDir + "Aspose.one");
// Initialize PdfSaveOptions object
PdfSaveOptions opts = new PdfSaveOptions
{
// Set page index of first page to be saved
PageIndex = 0,
// Set page count
PageCount = 1,
};
// Save the document as PDF
dataDir = dataDir + "SaveRangeOfPagesAsPDF_out.pdf";
oneFile.Save(dataDir, opts);
// Shows how to save a document in pdf format using specific settings.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document doc = new Document(dataDir + "Aspose.one");
// Initialize PdfSaveOptions object
PdfSaveOptions opts = new PdfSaveOptions
{
// Use Jpeg compression
ImageCompression = Saving.Pdf.PdfImageCompression.Jpeg,
// Quality for JPEG compression
JpegQuality = 90
};
dataDir = dataDir + "Document.SaveWithOptions_out.pdf";
doc.Save(dataDir, opts);
// Shows how to save a document as binary image using Otsu's method.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document oneFile = new Document(dataDir + "Aspose.one");
dataDir = dataDir + "SaveToBinaryImageUsingOtsuMethod_out.png";
// Save the document as gif.
oneFile.Save(dataDir, new ImageSaveOptions(SaveFormat.Png)
{
ColorMode = ColorMode.BlackAndWhite,
BinarizationOptions = new ImageBinarizationOptions()
{
BinarizationMethod = BinarizationMethod.Otsu,
}
});
// Shows how to save a document as binary image using fixed threshold.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document oneFile = new Document(dataDir + "Aspose.one");
dataDir = dataDir + "SaveToBinaryImageUsingFixedThreshold_out.png";
// Save the document as gif.
oneFile.Save(dataDir, new ImageSaveOptions(SaveFormat.Png)
{
ColorMode = ColorMode.BlackAndWhite,
BinarizationOptions = new ImageBinarizationOptions()
{
BinarizationMethod = BinarizationMethod.FixedThreshold,
BinarizationThreshold = 123
}
});
Exceptions
IncorrectDocumentStructureException
UnsupportedSaveFormatException
Save Document to Stream Using SaveOptions
public void Save(Stream stream, SaveOptions options)
Parameters
stream
Stream – The stream where the document will be saved.options
SaveOptions
Examples
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
// Load the document into Aspose.Note.
Document oneFile = new Document(Path.Combine(dataDir, "missing-font.one"));
// Save the document as PDF using a default font.
dataDir = dataDir + "SaveUsingDocumentFontsSubsystemWithDefaultFontName_out.pdf";
oneFile.Save(dataDir, new PdfSaveOptions()
{
FontsSubsystem = DocumentFontsSubsystem.UsingDefaultFont("Times New Roman")
});
// Shows how to save a document in pdf format using default font from a file.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fontFile = Path.Combine(dataDir, "geo_1.ttf");
// Load the document into Aspose.Note.
Document oneFile = new Document(Path.Combine(dataDir, "missing-font.one"));
// Save the document as PDF using a default font from a file.
dataDir = dataDir + "SaveUsingDocumentFontsSubsystemWithDefaultFontFromFile_out.pdf";
oneFile.Save(dataDir, new PdfSaveOptions()
{
FontsSubsystem = DocumentFontsSubsystem.UsingDefaultFontFromFile(fontFile)
});
// Shows how to save a document in pdf format using default font from a stream.
string dataDir = RunExamples.GetDataDir_LoadingAndSaving();
string fontFile = Path.Combine(dataDir, "geo_1.ttf");
// Load the document into Aspose.Note.
Document oneFile = new Document(Path.Combine(dataDir, "missing-font.one"));
// Save the document as PDF using a default font from a stream.
dataDir = dataDir + "SaveUsingDocumentFontsSubsystemWithDefaultFontFromStream_out.pdf";
using (var stream = File.Open(fontFile, FileMode.Open, FileAccess.Read, FileShare.Read))
{
oneFile.Save(dataDir, new PdfSaveOptions()
{
FontsSubsystem = DocumentFontsSubsystem.UsingDefaultFontFromStream(stream)
});
}
Exceptions
IncorrectDocumentStructureException
UnsupportedSaveFormatException