public abstract class DocumentBase extends CompositeNode
To learn more, visit the Aspose.Words Document Object Model (DOM) documentation article.
Remarks:
Aspose.Words represents a Word document as a tree of nodes. DocumentBase is a root node of the tree that contains all other nodes of the document.
DocumentBase also stores document-wide information such as getStyles() and getLists() that the tree nodes might refer to.
Examples:
Shows how to initialize the subclasses of DocumentBase.
Document doc = new Document();
Assert.assertEquals(DocumentBase.class, doc.getClass().getSuperclass());
GlossaryDocument glossaryDoc = new GlossaryDocument();
doc.setGlossaryDocument(glossaryDoc);
Assert.assertEquals(DocumentBase.class, glossaryDoc.getClass().getSuperclass());
Document,
DocumentBase| Modifier and Type | Field and Description |
|---|---|
protected java.util.HashMap |
mImageTransparencyFlagCache |
| Modifier | Constructor and Description |
|---|---|
protected |
DocumentBase()
Initializes a new instance of this class.
|
| Modifier and Type | Method and Description |
|---|---|
Shape |
getBackgroundShape()
Gets the background shape of the document.
|
DocumentBase |
getDocument()
Gets this instance.
|
FontInfoCollection |
getFontInfos()
Provides access to properties of fonts used in this document.
|
FootnoteSeparatorCollection |
getFootnoteSeparators()
Provides access to the footnote/endnote separators defined in the document.
|
ListCollection |
getLists()
Provides access to the list formatting used in the document.
|
INodeChangingCallback |
getNodeChangingCallback()
Called when a node is inserted or removed in the document.
|
java.awt.Color |
getPageColor()
Gets the page color of the document.
|
IResourceLoadingCallback |
getResourceLoadingCallback()
Allows to control how external resources are loaded.
|
StyleCollection |
getStyles()
Returns a collection of styles defined in the document.
|
IWarningCallback |
getWarningCallback()
Called during various document processing procedures when an issue is detected that might result in data or formatting fidelity loss.
|
Node |
importNode(Node srcNode,
boolean isImportChildren)
|
Node |
importNode(Node srcNode,
boolean isImportChildren,
int importFormatMode) |
protected void |
resetState() |
void |
setBackgroundShape(Shape value)
Sets the background shape of the document.
|
void |
setNodeChangingCallback(INodeChangingCallback value)
Called when a node is inserted or removed in the document.
|
void |
setPageColor(java.awt.Color value)
Sets the page color of the document.
|
void |
setResourceLoadingCallback(IResourceLoadingCallback value)
Allows to control how external resources are loaded.
|
void |
setWarningCallback(IWarningCallback value)
Called during various document processing procedures when an issue is detected that might result in data or formatting fidelity loss.
|
acceptChildren, acceptCore, acceptEnd, acceptStart, appendChild, coreRemoveSelfOnly, getChild, getChildNodes, getContainer, getCount, getCurrentNode, getFirstChild, getLastChild, getNextMatchingNode, getText, hasChildNodes, indexOf, insertAfter, insertBefore, isComposite, iterator, prependChild, removeAllChildren, removeChild, removeSmartTags, selectNodes, selectSingleNodeaccept, deepClone, getAncestor, getAncestor, getCustomNodeId, getNextSibling, getNodeType, getParentNode, getPreviousSibling, getRange, memberwiseClone, nextPreOrder, nodeTypeToString, previousPreOrder, remove, setCustomNodeId, toString, toString, toString, visitorActionToBoolprotected void resetState()
public Node importNode(Node srcNode, boolean isImportChildren)
Imports a node from another document to the current document.
Remarks:
This method uses the ImportFormatMode.USE_DESTINATION_STYLES option to resolve formatting.
Importing a node creates a copy of the source node belonging to the importing document. The returned node has no parent. The source node is not altered or removed from the original document.
Before a node from another document can be inserted into this document, it must be imported. During import, document-specific properties such as references to styles and lists are translated from the original to the importing document. After the node was imported, it can be inserted into the appropriate place in the document using CompositeNode.insertBefore(com.aspose.words.Node, com.aspose.words.Node) or CompositeNode.insertAfter(com.aspose.words.Node, com.aspose.words.Node).
If the source node already belongs to the destination document, then simply a deep clone of the source node is created.
Examples:
Shows how to import a node from one document to another.
Document srcDoc = new Document();
Document dstDoc = new Document();
srcDoc.getFirstSection().getBody().getFirstParagraph().appendChild(
new Run(srcDoc, "Source document first paragraph text."));
dstDoc.getFirstSection().getBody().getFirstParagraph().appendChild(
new Run(dstDoc, "Destination document first paragraph text."));
// Every node has a parent document, which is the document that contains the node.
// Inserting a node into a document that the node does not belong to will throw an exception.
Assert.assertNotEquals(dstDoc, srcDoc.getFirstSection().getDocument());
Assert.assertThrows(IllegalArgumentException.class, () -> dstDoc.appendChild(srcDoc.getFirstSection()));
// Use the ImportNode method to create a copy of a node, which will have the document
// that called the ImportNode method set as its new owner document.
Section importedSection = (Section) dstDoc.importNode(srcDoc.getFirstSection(), true);
Assert.assertEquals(dstDoc, importedSection.getDocument());
// We can now insert the node into the document.
dstDoc.appendChild(importedSection);
Assert.assertEquals("Destination document first paragraph text.\r\nSource document first paragraph text.\r\n",
dstDoc.toString(SaveFormat.TEXT));
srcNode - The node being imported.isImportChildren - true to import all child nodes recursively; otherwise, false.NodeImporterpublic DocumentBase getDocument()
Examples:
Shows how to create simple document.
Document doc = new Document();
// New Document objects by default come with the minimal set of nodes
// required to begin adding content such as text and shapes: a Section, a Body, and a Paragraph.
doc.appendChild(new Section(doc))
.appendChild(new Body(doc))
.appendChild(new Paragraph(doc))
.appendChild(new Run(doc, "Hello world!"));
getDocument in class Nodepublic INodeChangingCallback getNodeChangingCallback()
Examples:
Shows how customize node changing with a callback.
public void fontChangeViaCallback() throws Exception {
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Set the node changing callback to custom implementation,
// then add/remove nodes to get it to generate a log.
HandleNodeChangingFontChanger callback = new HandleNodeChangingFontChanger();
doc.setNodeChangingCallback(callback);
builder.writeln("Hello world!");
builder.writeln("Hello again!");
builder.insertField(" HYPERLINK \"https://www.google.com/\" ");
builder.insertShape(ShapeType.RECTANGLE, 300.0, 300.0);
doc.getRange().getFields().get(0).remove();
System.out.println(callback.getLog());
}
/// <summary>
/// Logs the date and time of each node insertion and removal.
/// Sets a custom font name/size for the text contents of Run nodes.
/// </summary>
public static class HandleNodeChangingFontChanger implements INodeChangingCallback {
public void nodeInserted(NodeChangingArgs args) {
mLog.append(MessageFormat.format("\tType:\t{0}", args.getNode().getNodeType()));
mLog.append(MessageFormat.format("\tHash:\t{0}", args.getNode().hashCode()));
if (args.getNode().getNodeType() == NodeType.RUN) {
Font font = ((Run) args.getNode()).getFont();
mLog.append(MessageFormat.format("\tFont:\tChanged from \"{0}\" {1}pt", font.getName(), font.getSize()));
font.setSize(24.0);
font.setName("Arial");
mLog.append(MessageFormat.format(" to \"{0}\" {1}pt", font.getName(), font.getSize()));
mLog.append(MessageFormat.format("\tContents:\n\t\t\"{0}\"", args.getNode().getText()));
}
}
public void nodeInserting(NodeChangingArgs args) {
mLog.append(MessageFormat.format("\n{0}\tNode insertion:", new Date()));
}
public void nodeRemoved(NodeChangingArgs args) {
mLog.append(MessageFormat.format("\tType:\t{0}", args.getNode().getNodeType()));
mLog.append(MessageFormat.format("\tHash code:\t{0}", args.getNode().hashCode()));
}
public void nodeRemoving(NodeChangingArgs args) {
mLog.append(MessageFormat.format("\n{0}\tNode removal:", new Date()));
}
public String getLog() {
return mLog.toString();
}
private final StringBuilder mLog = new StringBuilder();
}
INodeChangingCallback value.public void setNodeChangingCallback(INodeChangingCallback value)
Examples:
Shows how customize node changing with a callback.
public void fontChangeViaCallback() throws Exception {
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Set the node changing callback to custom implementation,
// then add/remove nodes to get it to generate a log.
HandleNodeChangingFontChanger callback = new HandleNodeChangingFontChanger();
doc.setNodeChangingCallback(callback);
builder.writeln("Hello world!");
builder.writeln("Hello again!");
builder.insertField(" HYPERLINK \"https://www.google.com/\" ");
builder.insertShape(ShapeType.RECTANGLE, 300.0, 300.0);
doc.getRange().getFields().get(0).remove();
System.out.println(callback.getLog());
}
/// <summary>
/// Logs the date and time of each node insertion and removal.
/// Sets a custom font name/size for the text contents of Run nodes.
/// </summary>
public static class HandleNodeChangingFontChanger implements INodeChangingCallback {
public void nodeInserted(NodeChangingArgs args) {
mLog.append(MessageFormat.format("\tType:\t{0}", args.getNode().getNodeType()));
mLog.append(MessageFormat.format("\tHash:\t{0}", args.getNode().hashCode()));
if (args.getNode().getNodeType() == NodeType.RUN) {
Font font = ((Run) args.getNode()).getFont();
mLog.append(MessageFormat.format("\tFont:\tChanged from \"{0}\" {1}pt", font.getName(), font.getSize()));
font.setSize(24.0);
font.setName("Arial");
mLog.append(MessageFormat.format(" to \"{0}\" {1}pt", font.getName(), font.getSize()));
mLog.append(MessageFormat.format("\tContents:\n\t\t\"{0}\"", args.getNode().getText()));
}
}
public void nodeInserting(NodeChangingArgs args) {
mLog.append(MessageFormat.format("\n{0}\tNode insertion:", new Date()));
}
public void nodeRemoved(NodeChangingArgs args) {
mLog.append(MessageFormat.format("\tType:\t{0}", args.getNode().getNodeType()));
mLog.append(MessageFormat.format("\tHash code:\t{0}", args.getNode().hashCode()));
}
public void nodeRemoving(NodeChangingArgs args) {
mLog.append(MessageFormat.format("\n{0}\tNode removal:", new Date()));
}
public String getLog() {
return mLog.toString();
}
private final StringBuilder mLog = new StringBuilder();
}
value - The corresponding INodeChangingCallback value.public IResourceLoadingCallback getResourceLoadingCallback()
Examples:
Shows how to customize the process of loading external resources into a document.
public void resourceLoadingCallback() throws Exception {
Document doc = new Document();
doc.setResourceLoadingCallback(new ImageNameHandler());
DocumentBuilder builder = new DocumentBuilder(doc);
// Images usually are inserted using a URI, or a byte array.
// Every instance of a resource load will call our callback's ResourceLoading method.
builder.insertImage("Google logo");
builder.insertImage("Aspose logo");
builder.insertImage("Watermark");
Assert.assertEquals(3, doc.getChildNodes(NodeType.SHAPE, true).getCount());
doc.save(getArtifactsDir() + "DocumentBase.ResourceLoadingCallback.docx");
}
/// <summary>
/// Allows us to load images into a document using predefined shorthands, as opposed to URIs.
/// This will separate image loading logic from the rest of the document construction.
/// </summary>
private static class ImageNameHandler implements IResourceLoadingCallback {
public int resourceLoading(final ResourceLoadingArgs args) throws URISyntaxException, IOException {
if (args.getResourceType() == ResourceType.IMAGE) {
// If this callback encounters one of the image shorthands while loading an image,
// it will apply unique logic for each defined shorthand instead of treating it as a URI.
if ("Google logo".equals(args.getOriginalUri())) {
args.setData(DocumentHelper.getBytesFromStream(new URI("http://www.google.com/images/logos/ps_logo2.png").toURL().openStream()));
return ResourceLoadingAction.USER_PROVIDED;
}
if ("Aspose logo".equals(args.getOriginalUri())) {
args.setData(DocumentHelper.getBytesFromStream(getAsposelogoUri().toURL().openStream()));
return ResourceLoadingAction.USER_PROVIDED;
}
if ("Watermark".equals(args.getOriginalUri())) {
InputStream imageStream = new FileInputStream(getImageDir() + "Transparent background logo.png");
args.setData(DocumentHelper.getBytesFromStream(imageStream));
return ResourceLoadingAction.USER_PROVIDED;
}
}
return ResourceLoadingAction.DEFAULT;
}
}
IResourceLoadingCallback value.public void setResourceLoadingCallback(IResourceLoadingCallback value)
Examples:
Shows how to customize the process of loading external resources into a document.
public void resourceLoadingCallback() throws Exception {
Document doc = new Document();
doc.setResourceLoadingCallback(new ImageNameHandler());
DocumentBuilder builder = new DocumentBuilder(doc);
// Images usually are inserted using a URI, or a byte array.
// Every instance of a resource load will call our callback's ResourceLoading method.
builder.insertImage("Google logo");
builder.insertImage("Aspose logo");
builder.insertImage("Watermark");
Assert.assertEquals(3, doc.getChildNodes(NodeType.SHAPE, true).getCount());
doc.save(getArtifactsDir() + "DocumentBase.ResourceLoadingCallback.docx");
}
/// <summary>
/// Allows us to load images into a document using predefined shorthands, as opposed to URIs.
/// This will separate image loading logic from the rest of the document construction.
/// </summary>
private static class ImageNameHandler implements IResourceLoadingCallback {
public int resourceLoading(final ResourceLoadingArgs args) throws URISyntaxException, IOException {
if (args.getResourceType() == ResourceType.IMAGE) {
// If this callback encounters one of the image shorthands while loading an image,
// it will apply unique logic for each defined shorthand instead of treating it as a URI.
if ("Google logo".equals(args.getOriginalUri())) {
args.setData(DocumentHelper.getBytesFromStream(new URI("http://www.google.com/images/logos/ps_logo2.png").toURL().openStream()));
return ResourceLoadingAction.USER_PROVIDED;
}
if ("Aspose logo".equals(args.getOriginalUri())) {
args.setData(DocumentHelper.getBytesFromStream(getAsposelogoUri().toURL().openStream()));
return ResourceLoadingAction.USER_PROVIDED;
}
if ("Watermark".equals(args.getOriginalUri())) {
InputStream imageStream = new FileInputStream(getImageDir() + "Transparent background logo.png");
args.setData(DocumentHelper.getBytesFromStream(imageStream));
return ResourceLoadingAction.USER_PROVIDED;
}
}
return ResourceLoadingAction.DEFAULT;
}
}
value - The corresponding IResourceLoadingCallback value.public FontInfoCollection getFontInfos()
Remarks:
This collection of font definitions is loaded as is from the document. Font definitions might be optional, missing or incomplete in some documents.
Do not rely on this collection to ascertain that a particular font is used in the document. You should only use this collection to get information about fonts that might be used in the document.
Examples:
Shows how to save a document with embedded TrueType fonts.
Document doc = new Document(getMyDir() + "Document.docx");
FontInfoCollection fontInfos = doc.getFontInfos();
fontInfos.setEmbedTrueTypeFonts(embedAllFonts);
fontInfos.setEmbedSystemFonts(embedAllFonts);
fontInfos.setSaveSubsetFonts(embedAllFonts);
doc.save(getArtifactsDir() + "Font.FontInfoCollection.docx");
Shows how to print the details of what fonts are present in a document.
Document doc = new Document(getMyDir() + "Embedded font.docx");
FontInfoCollection allFonts = doc.getFontInfos();
// Print all the used and unused fonts in the document.
for (int i = 0; i < allFonts.getCount(); i++) {
System.out.println("Font index #{i}");
System.out.println("\tName: {allFonts[i].Name}");
}
FontInfoCollection value.FontInfoCollection,
FontInfopublic StyleCollection getStyles()
Remarks:
For more information see the description of the StyleCollection class.
Examples:
Shows how to access a document's style collection.
Document doc = new Document();
Assert.assertEquals(4, doc.getStyles().getCount());
// Enumerate and list all the styles that a document created using Aspose.Words contains by default.
Iterator<Style> stylesEnum = doc.getStyles().iterator();
while (stylesEnum.hasNext()) {
Style curStyle = stylesEnum.next();
System.out.println(MessageFormat.format("Style name:\t\"{0}\", of type \"{1}\"", curStyle.getName(), curStyle.getType()));
System.out.println(MessageFormat.format("\tSubsequent style:\t{0}", curStyle.getNextParagraphStyleName()));
System.out.println(MessageFormat.format("\tIs heading:\t\t\t{0}", curStyle.isHeading()));
System.out.println(MessageFormat.format("\tIs QuickStyle:\t\t{0}", curStyle.isQuickStyle()));
Assert.assertEquals(curStyle.getDocument(), doc);
}
Shows how to create and use a paragraph style with list formatting.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Create a custom paragraph style.
Style style = doc.getStyles().add(StyleType.PARAGRAPH, "MyStyle1");
style.getFont().setSize(24.0);
style.getFont().setName("Verdana");
style.getParagraphFormat().setSpaceAfter(12.0);
// Create a list and make sure the paragraphs that use this style will use this list.
style.getListFormat().setList(doc.getLists().add(ListTemplate.BULLET_DEFAULT));
style.getListFormat().setListLevelNumber(0);
// Apply the paragraph style to the document builder's current paragraph, and then add some text.
builder.getParagraphFormat().setStyle(style);
builder.writeln("Hello World: MyStyle1, bulleted list.");
// Change the document builder's style to one that has no list formatting and write another paragraph.
builder.getParagraphFormat().setStyle(doc.getStyles().get("Normal"));
builder.writeln("Hello World: Normal.");
builder.getDocument().save(getArtifactsDir() + "Styles.ParagraphStyleBulletedList.docx");
StyleCollection,
Stylepublic ListCollection getLists()
Remarks:
For more information see the description of the ListCollection class.
Examples:
Shows how to work with list levels.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Assert.assertFalse(builder.getListFormat().isListItem());
// A list allows us to organize and decorate sets of paragraphs with prefix symbols and indents.
// We can create nested lists by increasing the indent level.
// We can begin and end a list by using a document builder's "ListFormat" property.
// Each paragraph that we add between a list's start and the end will become an item in the list.
// Below are two types of lists that we can create using a document builder.
// 1 - A numbered list:
// Numbered lists create a logical order for their paragraphs by numbering each item.
builder.getListFormat().setList(doc.getLists().add(ListTemplate.NUMBER_DEFAULT));
Assert.assertTrue(builder.getListFormat().isListItem());
// By setting the "ListLevelNumber" property, we can increase the list level
// to begin a self-contained sub-list at the current list item.
// The Microsoft Word list template called "NumberDefault" uses numbers to create list levels for the first list level.
// Deeper list levels use letters and lowercase Roman numerals.
for (int i = 0; i < 9; i++) {
builder.getListFormat().setListLevelNumber(i);
builder.writeln("Level " + i);
}
// 2 - A bulleted list:
// This list will apply an indent and a bullet symbol ("•") before each paragraph.
// Deeper levels of this list will use different symbols, such as "■" and "○".
builder.getListFormat().setList(doc.getLists().add(ListTemplate.BULLET_DEFAULT));
for (int i = 0; i < 9; i++) {
builder.getListFormat().setListLevelNumber(i);
builder.writeln("Level " + i);
}
// We can disable list formatting to not format any subsequent paragraphs as lists by un-setting the "List" flag.
builder.getListFormat().setList(null);
Assert.assertFalse(builder.getListFormat().isListItem());
doc.save(getArtifactsDir() + "Lists.SpecifyListLevel.docx");
ListCollection value.ListCollection,
List,
ListFormatpublic IWarningCallback getWarningCallback()
Remarks:
Document may generate warnings at any stage of its existence, so it's important to setup warning callback as early as possible to avoid the warnings loss. E.g. such properties as Document.getPageCount() actually build the document layout which is used later for rendering, and the layout warnings may be lost if warning callback is specified just for the rendering calls later.
Examples:
Shows how to set the property for finding the closest match for a missing font from the available font sources.
// Open a document that contains text formatted with a font that does not exist in any of our font sources.
Document doc = new Document(getMyDir() + "Missing font.docx");
// Assign a callback for handling font substitution warnings.
WarningInfoCollection warningCollector = new WarningInfoCollection();
doc.setWarningCallback(warningCollector);
// Set a default font name and enable font substitution.
FontSettings fontSettings = new FontSettings();
fontSettings.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Arial");
fontSettings.getSubstitutionSettings().getFontInfoSubstitution().setEnabled(true);
// Original font metrics should be used after font substitution.
doc.getLayoutOptions().setKeepOriginalFontMetrics(true);
// We will get a font substitution warning if we save a document with a missing font.
doc.setFontSettings(fontSettings);
doc.save(getArtifactsDir() + "FontSettings.EnableFontSubstitution.pdf");
for (WarningInfo info : warningCollector)
{
if (info.getWarningType() == WarningType.FONT_SUBSTITUTION)
System.out.println(info.getDescription());
}
Shows how to use the IWarningCallback interface to monitor font substitution warnings.
public void substitutionWarning() throws Exception {
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.getFont().setName("Times New Roman");
builder.writeln("Hello world!");
FontSubstitutionWarningCollector callback = new FontSubstitutionWarningCollector();
doc.setWarningCallback(callback);
// Store the current collection of font sources, which will be the default font source for every document
// for which we do not specify a different font source.
FontSourceBase[] originalFontSources = FontSettings.getDefaultInstance().getFontsSources();
// For testing purposes, we will set Aspose.Words to look for fonts only in a folder that does not exist.
FontSettings.getDefaultInstance().setFontsFolder("", false);
// When rendering the document, there will be no place to find the "Times New Roman" font.
// This will cause a font substitution warning, which our callback will detect.
doc.save(getArtifactsDir() + "FontSettings.SubstitutionWarning.pdf");
FontSettings.getDefaultInstance().setFontsSources(originalFontSources);
Assert.assertTrue(callback.FontSubstitutionWarnings.get(0).getWarningType() == WarningType.FONT_SUBSTITUTION);
Assert.assertTrue(callback.FontSubstitutionWarnings.get(0).getDescription()
.equals("Font 'Times New Roman' has not been found. Using 'Fanwood' font instead. Reason: first available font."));
}
private static class FontSubstitutionWarningCollector implements IWarningCallback {
/// <summary>
/// Called every time a warning occurs during loading/saving.
/// </summary>
public void warning(WarningInfo info) {
if (info.getWarningType() == WarningType.FONT_SUBSTITUTION)
FontSubstitutionWarnings.warning(info);
}
public WarningInfoCollection FontSubstitutionWarnings = new WarningInfoCollection();
}
IWarningCallback value.public void setWarningCallback(IWarningCallback value)
Remarks:
Document may generate warnings at any stage of its existence, so it's important to setup warning callback as early as possible to avoid the warnings loss. E.g. such properties as Document.getPageCount() actually build the document layout which is used later for rendering, and the layout warnings may be lost if warning callback is specified just for the rendering calls later.
Examples:
Shows how to set the property for finding the closest match for a missing font from the available font sources.
// Open a document that contains text formatted with a font that does not exist in any of our font sources.
Document doc = new Document(getMyDir() + "Missing font.docx");
// Assign a callback for handling font substitution warnings.
WarningInfoCollection warningCollector = new WarningInfoCollection();
doc.setWarningCallback(warningCollector);
// Set a default font name and enable font substitution.
FontSettings fontSettings = new FontSettings();
fontSettings.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Arial");
fontSettings.getSubstitutionSettings().getFontInfoSubstitution().setEnabled(true);
// Original font metrics should be used after font substitution.
doc.getLayoutOptions().setKeepOriginalFontMetrics(true);
// We will get a font substitution warning if we save a document with a missing font.
doc.setFontSettings(fontSettings);
doc.save(getArtifactsDir() + "FontSettings.EnableFontSubstitution.pdf");
for (WarningInfo info : warningCollector)
{
if (info.getWarningType() == WarningType.FONT_SUBSTITUTION)
System.out.println(info.getDescription());
}
Shows how to use the IWarningCallback interface to monitor font substitution warnings.
public void substitutionWarning() throws Exception {
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.getFont().setName("Times New Roman");
builder.writeln("Hello world!");
FontSubstitutionWarningCollector callback = new FontSubstitutionWarningCollector();
doc.setWarningCallback(callback);
// Store the current collection of font sources, which will be the default font source for every document
// for which we do not specify a different font source.
FontSourceBase[] originalFontSources = FontSettings.getDefaultInstance().getFontsSources();
// For testing purposes, we will set Aspose.Words to look for fonts only in a folder that does not exist.
FontSettings.getDefaultInstance().setFontsFolder("", false);
// When rendering the document, there will be no place to find the "Times New Roman" font.
// This will cause a font substitution warning, which our callback will detect.
doc.save(getArtifactsDir() + "FontSettings.SubstitutionWarning.pdf");
FontSettings.getDefaultInstance().setFontsSources(originalFontSources);
Assert.assertTrue(callback.FontSubstitutionWarnings.get(0).getWarningType() == WarningType.FONT_SUBSTITUTION);
Assert.assertTrue(callback.FontSubstitutionWarnings.get(0).getDescription()
.equals("Font 'Times New Roman' has not been found. Using 'Fanwood' font instead. Reason: first available font."));
}
private static class FontSubstitutionWarningCollector implements IWarningCallback {
/// <summary>
/// Called every time a warning occurs during loading/saving.
/// </summary>
public void warning(WarningInfo info) {
if (info.getWarningType() == WarningType.FONT_SUBSTITUTION)
FontSubstitutionWarnings.warning(info);
}
public WarningInfoCollection FontSubstitutionWarnings = new WarningInfoCollection();
}
value - The corresponding IWarningCallback value.public FootnoteSeparatorCollection getFootnoteSeparators()
Examples:
Shows how to remove endnote separator.
Document doc = new Document(getMyDir() + "Footnotes and endnotes.docx");
FootnoteSeparator endnoteSeparator = doc.getFootnoteSeparators().getByFootnoteSeparatorType(FootnoteSeparatorType.ENDNOTE_SEPARATOR);
// Remove endnote separator.
endnoteSeparator.getFirstParagraph().getFirstChild().remove();
Shows how to manage footnote separator format.
Document doc = new Document(getMyDir() + "Footnotes and endnotes.docx");
FootnoteSeparator footnoteSeparator = doc.getFootnoteSeparators().getByFootnoteSeparatorType(FootnoteSeparatorType.FOOTNOTE_SEPARATOR);
// Align footnote separator.
footnoteSeparator.getFirstParagraph().getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
FootnoteSeparatorCollection value.public Shape getBackgroundShape()
null.
Remarks:
Microsoft Word allows only a shape that has its ShapeBase.getShapeType() property equal to ShapeType.RECTANGLE to be used as a background shape for a document.
Microsoft Word supports only the fill properties of a background shape. All other properties are ignored.
Setting this property to a non-null value will also set the ViewOptions.getDisplayBackgroundShape() / ViewOptions.setDisplayBackgroundShape(boolean) to true.
Examples:
Shows how to set a background shape for every page of a document.
Document doc = new Document();
Assert.assertNull(doc.getBackgroundShape());
// The only shape type that we can use as a background is a rectangle.
Shape shapeRectangle = new Shape(doc, ShapeType.RECTANGLE);
// There are two ways of using this shape as a page background.
// 1 - A flat color:
shapeRectangle.setFillColor(Color.BLUE);
doc.setBackgroundShape(shapeRectangle);
doc.save(getArtifactsDir() + "DocumentBase.BackgroundShape.FlatColor.docx");
// 2 - An image:
shapeRectangle = new Shape(doc, ShapeType.RECTANGLE);
shapeRectangle.getImageData().setImage(getImageDir() + "Transparent background logo.png");
// Adjust the image's appearance to make it more suitable as a watermark.
shapeRectangle.getImageData().setContrast(0.2);
shapeRectangle.getImageData().setBrightness(0.7);
doc.setBackgroundShape(shapeRectangle);
Assert.assertTrue(doc.getBackgroundShape().hasImage());
PdfSaveOptions saveOptions = new PdfSaveOptions();
saveOptions.setCacheBackgroundGraphics(false);
// Microsoft Word does not support shapes with images as backgrounds,
// but we can still see these backgrounds in other save formats such as .pdf.
doc.save(getArtifactsDir() + "DocumentBase.BackgroundShape.Image.pdf", saveOptions);
ViewOptions.getDisplayBackgroundShape(),
ViewOptions.setDisplayBackgroundShape(boolean),
getPageColor(),
setPageColor(java.awt.Color)public void setBackgroundShape(Shape value)
null.
Remarks:
Microsoft Word allows only a shape that has its ShapeBase.getShapeType() property equal to ShapeType.RECTANGLE to be used as a background shape for a document.
Microsoft Word supports only the fill properties of a background shape. All other properties are ignored.
Setting this property to a non-null value will also set the ViewOptions.getDisplayBackgroundShape() / ViewOptions.setDisplayBackgroundShape(boolean) to true.
Examples:
Shows how to set a background shape for every page of a document.
Document doc = new Document();
Assert.assertNull(doc.getBackgroundShape());
// The only shape type that we can use as a background is a rectangle.
Shape shapeRectangle = new Shape(doc, ShapeType.RECTANGLE);
// There are two ways of using this shape as a page background.
// 1 - A flat color:
shapeRectangle.setFillColor(Color.BLUE);
doc.setBackgroundShape(shapeRectangle);
doc.save(getArtifactsDir() + "DocumentBase.BackgroundShape.FlatColor.docx");
// 2 - An image:
shapeRectangle = new Shape(doc, ShapeType.RECTANGLE);
shapeRectangle.getImageData().setImage(getImageDir() + "Transparent background logo.png");
// Adjust the image's appearance to make it more suitable as a watermark.
shapeRectangle.getImageData().setContrast(0.2);
shapeRectangle.getImageData().setBrightness(0.7);
doc.setBackgroundShape(shapeRectangle);
Assert.assertTrue(doc.getBackgroundShape().hasImage());
PdfSaveOptions saveOptions = new PdfSaveOptions();
saveOptions.setCacheBackgroundGraphics(false);
// Microsoft Word does not support shapes with images as backgrounds,
// but we can still see these backgrounds in other save formats such as .pdf.
doc.save(getArtifactsDir() + "DocumentBase.BackgroundShape.Image.pdf", saveOptions);
value - The background shape of the document.ViewOptions.getDisplayBackgroundShape(),
ViewOptions.setDisplayBackgroundShape(boolean),
getPageColor(),
setPageColor(java.awt.Color)public java.awt.Color getPageColor()
getBackgroundShape() / setBackgroundShape(com.aspose.words.Shape).
Remarks:
This property provides a simple way to specify a solid page color for the document. Setting this property creates and sets an appropriate getBackgroundShape() / setBackgroundShape(com.aspose.words.Shape).
If the page color is not set (e.g. there is no background shape in the document) returns a zero color.
Examples:
Shows how to set the background color for all pages of a document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Hello world!");
doc.setPageColor(Color.lightGray);
doc.save(getArtifactsDir() + "DocumentBase.SetPageColor.docx");
getBackgroundShape(),
setBackgroundShape(com.aspose.words.Shape)public void setPageColor(java.awt.Color value)
getBackgroundShape() / setBackgroundShape(com.aspose.words.Shape).
Remarks:
This property provides a simple way to specify a solid page color for the document. Setting this property creates and sets an appropriate getBackgroundShape() / setBackgroundShape(com.aspose.words.Shape).
If the page color is not set (e.g. there is no background shape in the document) returns a zero color.
Examples:
Shows how to set the background color for all pages of a document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.writeln("Hello world!");
doc.setPageColor(Color.lightGray);
doc.save(getArtifactsDir() + "DocumentBase.SetPageColor.docx");
value - The page color of the document.getBackgroundShape(),
setBackgroundShape(com.aspose.words.Shape)