Thursday, 06 June 2019 09:15

Merge Word Documents in Java

This article demonstrates how to merge Word documents using Spire.Doc for Java.

Document class provides an insertTextFromFile() method that let us merge Word documents by inserting content from a source document into a destination document. In the result document, the inserted content will start from a new page.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class MergeWordDocument {
    public static void main(String[] args){

        //File path of the first document
        String filePath1 = "merge1.docx";
        //File path of the second document
        String filePath2 = "merge2.docx";

        //Load the first document
        Document document = new Document(filePath1);

        //Insert content of the second document into the first document
        document.insertTextFromFile(filePath2, FileFormat.Docx_2013);

        //Save the resultant document
        document.saveToFile("Output.docx", FileFormat.Docx_2013);       

    }
}

Output:

Merge Word Documents in Java

If you want the inserted content to follow the last paragraph of the destination document instead of starting from a new page, use the below method to clone sections of the source document and then append to the last section of the destination document.

import com.spire.doc.Document;
import com.spire.doc.DocumentObject;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;

public class MergeWordDocument {
    public static void main(String[] args){

        //File path of the first document
        String filePath1 = "merge1.docx";
        //File path of the second document
        String filePath2 = "merge2.docx";

        //Load the first document
        Document document1 = new Document(filePath1);
        //Load the second document
        Document document2 = new Document(filePath2);

        //Get the last section of the first document
        Section lastSection = document1.getLastSection();

        //Add the sections of the second document to the last section of the first document
        for (Section section:(Iterable )document2.getSections()) {
            for (DocumentObject obj:(Iterable )section.getBody().getChildObjects()
                 ) {
                lastSection.getBody().getChildObjects().add(obj.deepClone());
            }
        }

        //Save the resultant document
        document1.saveToFile("Output.docx", FileFormat.Docx_2013);

    }
}

Output:

Merge Word Documents in Java

Wednesday, 05 June 2019 08:57

Insert footnote to word in Java

This article demonstrates how to insert footnote to a word document in Java applications with the help of Spire.Doc. We will show you how to add footnote by the following two parts.

  • Add a footnote to a paragraph in the word document.
  • Find a specified text string and insert footnote behinds it in the word document.

Add a footnote to the first paragraph in word:

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
import java.awt.*;


public class WordFootnote {
    public static void main(String[] args) throws Exception {
        //load sample word document
        Document doc = new Document();
        doc.loadFromFile("Sample.docx", FileFormat.Docx_2010);

        //get the first paragraph from the first section
        Paragraph para = doc.getSections().get(0).getParagraphs().get(0);

        //Add footnote to the first paragraph
        Footnote footnote = para.appendFootnote(FootnoteType.Footnote);

        //Add the text and format for it
        TextRange text = footnote.getTextBody().addParagraph().appendText("Demo of Spire.Doc");
        text.getCharacterFormat().setFontName("Arial Black");
        text.getCharacterFormat().setFontSize(10);
        text.getCharacterFormat().setTextColor(new Color(255, 140, 0));

        //set the format for footnote marker
        footnote.getMarkerCharacterFormat().setFontName("Calibri");
        footnote.getMarkerCharacterFormat().setFontSize(12);
        footnote.getMarkerCharacterFormat().setBold(true);
        footnote.getMarkerCharacterFormat().setTextColor(new Color(0, 0, 139));

        // save the document to file
        doc.saveToFile("output/Addfootnote.docx", FileFormat.Docx_2010);

        }
    }

Effective screenshot after insert a footnote in the paragraph:

Insert footnote to word in Java

Find “Spire.Doc” and insert footnote behinds it in the word document

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
import java.awt.*;


public class WordFootnotes {
    public static void main(String[] args) throws Exception {
        //load sample word document
        Document doc = new Document();
        doc.loadFromFile("Sample.docx", FileFormat.Docx_2010);
        
        //find text string Spire.Doc in the whole word document
        TextSelection[] selections = doc.findAllString("Spire.Doc", false, true);
        for (TextSelection selection : selections) {
            TextRange range = selection.getAsOneRange();
            Paragraph para = range.getOwnerParagraph();

            //Add footnote behind the searched text strings
            Footnote footnote = para.appendFootnote(FootnoteType.Footnote);
            int index = para.getChildObjects().indexOf(range);

            para.getChildObjects().insert(index + 1, footnote);

            //Add the text and format for it
            TextRange text = footnote.getTextBody().addParagraph().appendText("Demo of Spire.Doc");
            text.getCharacterFormat().setFontName("Arial Black");
            text.getCharacterFormat().setFontSize(10);
            text.getCharacterFormat().setTextColor(new Color(255, 140, 0));
            //set the format for footnote marker
            footnote.getMarkerCharacterFormat().setFontName("Calibri");
            footnote.getMarkerCharacterFormat().setFontSize(12);
            footnote.getMarkerCharacterFormat().setBold(true);
            footnote.getMarkerCharacterFormat().setTextColor(new Color(0, 0, 139));

            // save the document to file
            doc.saveToFile("output/Addfootnote.docx", FileFormat.Docx_2010);

        }
    }
}

Effective screenshot after insert footnotes to the searched text strings:

Insert footnote to word in Java

Tuesday, 04 June 2019 05:53

Print Word Document in Java

This article demonstrates how to print a Word document to a specific physical printer or virtual printer by using Spire.Doc for Java.

Print to Physical Printer

import com.spire.doc.Document;
import com.spire.ms.System.Drawing.Printing.PrinterSettings;

public class PrintWord {

    public static void main(String[] args) {

        //load a Word document that you want to print
        Document document = new Document();
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\DocoumentToPrint.docx");

        //create a PrinterSettings object
        PrinterSettings printerSettings = new PrinterSettings();

        //specify printer name
        printerSettings.setPrinterName("\\\\192.168.1.104\\HP LaserJet P1007");

        //set copies to print
        printerSettings.setCopies((short) 1);

        //set the page range to print
        printerSettings.setFromPage(2);
        printerSettings.setToPage(4);

        //apply printer settings
        document.getPrintDocument().setPrinterSettings(printerSettings);

        //execute print
        document.getPrintDocument().print();
    }
}

Print to PDF

import com.spire.doc.Document;
import com.spire.ms.System.Drawing.Printing.PrinterSettings;

public class PrintWord {

    public static void main(String[] args) {

        //load a Word document that you want to print
        Document document = new Document();
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\ToPrint.docx");

        //create a PrinterSettings object
        PrinterSettings printerSettings = new PrinterSettings();

        //specify virtual printer name
        printerSettings.setPrinterName("Microsoft Print to PDF");

        //print to file
        printerSettings.setPrintToFile(true);

        //specify path and name of the printed file
        printerSettings.setPrintFileName("output/PrintToPDF.pdf");

        //apply printer settings
        document.getPrintDocument().setPrinterSettings(printerSettings);

        //execute print
        document.getPrintDocument().print();
    }
}
Thursday, 08 November 2018 07:59

How to convert Word to PostScript in C#

PostScript is a page description language that is an industry standard for outputting high-resolution text and graphics. From Version 6.11.2, Spire.Doc supports to convert doc/docx to a postscript file in both WinForm app and ASP.NET app. This article will demonstrate how to convert word to PostScript in C# and VB.NET.

Firstly, view the sample word document:

How to convert Word to PostScript in C#

[C#]
using Spire.Doc;

namespace Word
{
    class Program
    {
        static void Main(string[] args)
        {            
            Document doc = new Document();
            doc.LoadFromFile("Sample.docx", FileFormat.Docx2010);
            doc.SaveToFile("Result.ps", FileFormat.PostScript);                 
        }
    }
}
[VB.NET]
Imports Spire.Doc
Namespace Word
    Class Program
        Private Shared Sub Main(ByVal args As String())
            Dim doc As Document = New Document()
            doc.LoadFromFile("Sample.docx", FileFormat.Docx2010)
            doc.SaveToFile("Result.ps", FileFormat.PostScript)
        End Sub
    End Class
End Namespace

Effective screenshot of the resulted PostScript file converted from .docx document:

How to convert Word to PostScript in C#

Thursday, 08 November 2018 06:05

Convert PDF to PDF/A in Java

This article demonstrates how to convert PDF to PDF/A using Spire.PDF for Java.

import com.spire.pdf.PdfConformanceLevel;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfNewDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfMargins;

import java.awt.geom.Dimension2D;

public class PDFToPDFA {
    public static void main(String[] args)
    {
        //Load pdf file
        PdfDocument document = new PdfDocument();
        document.loadFromFile("Sales Report.pdf");

        //Convert to Pdf_A_1_B
        PdfNewDocument newDoc = new PdfNewDocument();
        newDoc.setConformance(PdfConformanceLevel.Pdf_A_1_B);
        for (PdfPageBase page : (Iterable) document.getPages()) {
            Dimension2D size = page.getSize();
            PdfPageBase p = newDoc.getPages().add(size, new PdfMargins(0));
            page.createTemplate().draw(p, 0, 0);
        }

        //Save the file
        newDoc.save("Output.pdf");
        newDoc.close();
    }
}

Output:

Convert PDF to PDF/A in Java

Monday, 05 November 2018 07:09

Extract Images from PDF in Java

This tutorial shows how to extract images from a PDF document using Spire.PDF for Java.

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ExtractImages {

	public static void main(String[] args) throws IOException {

		//create a PdfDocment object
		PdfDocument doc = new PdfDocument();

		//load a PDF file
		doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Images.pdf");

		//declare an int variable
		int index = 0;

		//loop through the pages 
		for (PdfPageBase page : (Iterable<PdfPageBase>) doc.getPages()) { 


			//extract images from a particular page
			for (BufferedImage image : page.extractImages()) {

				//specify the file path and name 
				File output = new File("F:\\Documents\\ExtractedImages\\" + String.format("Image_%d.png", index++));

				//save image as .png file 
				ImageIO.write(image, "PNG", output);
			}
		}
	}
}

Output:

Extract Images from PDF in Java

Every PowerPoint presentation has a slide master which contains all the styles for your slides. You can quickly change the look of your entire presentation by selecting the slide master, and then adopting a theme, adding a background picture or changing the color scheme.

In this article, you will learn how to access and customize the slide master in an existing presentation.

Source File:

Apply a Slide Master to a Presentation in 

C#, VB.NET

Detail steps:

Step 1: Load the source file.

Presentation ppt = new Presentation();
ppt.LoadFromFile(@"sample.pptx");

Step 2: Get the first slide master from the presentation.

IMasterSlide masterSlide = ppt.Masters[0];

Step 3: Customize the background of the slide master.

string backgroundPic = "background.png";
RectangleF rect = new RectangleF(0, 0, ppt.SlideSize.Size.Width, ppt.SlideSize.Size.Height);
masterSlide.SlideBackground.Fill.FillType = FillFormatType.Picture;
IEmbedImage image = masterSlide.Shapes.AppendEmbedImage(ShapeType.Rectangle, backgroundPic, rect);
masterSlide.SlideBackground.Fill.PictureFill.Picture.EmbedImage = image as IImageData;

Step 4: Change the color scheme.

masterSlide.Theme.ColorScheme.Accent1.Color = Color.Red;
masterSlide.Theme.ColorScheme.Accent2.Color = Color.RosyBrown;
masterSlide.Theme.ColorScheme.Accent3.Color = Color.Ivory;
masterSlide.Theme.ColorScheme.Accent4.Color = Color.Lavender;
masterSlide.Theme.ColorScheme.Accent5.Color = Color.Black;

Step 5: Add an image to the slide master. If you want, you can add any other document elements to slide master so that they can display on each slide.

string logo = "logo.png";
IEmbedImage imageShape = masterSlide.Shapes.AppendEmbedImage(ShapeType.Rectangle, logo, new RectangleF(40, 40, 240, 65));
imageShape.Line.FillFormat.FillType = FillFormatType.None;

Step 6: Save the document.

ppt.SaveToFile("result.pptx", FileFormat.Pptx2013);

Result:

Apply a Slide Master to a Presentation in C#, VB.NET

Full code:

[C#]
Presentation ppt = new Presentation();
ppt.LoadFromFile(@"sample.pptx");

IMasterSlide masterSlide = ppt.Masters[0];
string backgroundPic = "background.png";
string logo = "logo.png";
RectangleF rect = new RectangleF(0, 0, ppt.SlideSize.Size.Width, ppt.SlideSize.Size.Height);
masterSlide.SlideBackground.Fill.FillType = FillFormatType.Picture;
IEmbedImage image = masterSlide.Shapes.AppendEmbedImage(ShapeType.Rectangle, backgroundPic, rect);
masterSlide.SlideBackground.Fill.PictureFill.Picture.EmbedImage = image as IImageData;
masterSlide.Theme.ColorScheme.Accent1.Color = Color.Red;
masterSlide.Theme.ColorScheme.Accent2.Color = Color.RosyBrown;
masterSlide.Theme.ColorScheme.Accent3.Color = Color.Ivory;
masterSlide.Theme.ColorScheme.Accent4.Color = Color.Lavender;
masterSlide.Theme.ColorScheme.Accent5.Color = Color.Black;
IEmbedImage imageShape = masterSlide.Shapes.AppendEmbedImage
(ShapeType.Rectangle, logo, new RectangleF(40, 40, 240, 65));
imageShape.Line.FillFormat.FillType = FillFormatType.None;

ppt.SaveToFile("result.pptx", FileFormat.Pptx2013);
[VB.NET]
Dim ppt As Presentation = New Presentation()
ppt.LoadFromFile("sample.pptx")
Dim masterSlide As IMasterSlide = ppt.Masters(0)
Dim backgroundPic As String = "background.png"
Dim logo As String = "logo.png"
Dim rect As RectangleF =  New RectangleF(0,0,ppt.SlideSize.Size.Width,ppt.SlideSize.Size.Height) 
masterSlide.SlideBackground.Fill.FillType = FillFormatType.Picture
Dim image As IEmbedImage =  masterSlide.Shapes.AppendEmbedImage(ShapeType.Rectangle,backgroundPic,rect) 
masterSlide.SlideBackground.Fill.PictureFill.Picture.EmbedImage = image as IImageData
masterSlide.Theme.ColorScheme.Accent1.Color = Color.Red
masterSlide.Theme.ColorScheme.Accent2.Color = Color.RosyBrown
masterSlide.Theme.ColorScheme.Accent3.Color = Color.Ivory
masterSlide.Theme.ColorScheme.Accent4.Color = Color.Lavender
masterSlide.Theme.ColorScheme.Accent5.Color = Color.Black
Dim imageShape As IEmbedImage = masterSlide.Shapes.AppendEmbedImage(ShapeType.Rectangle, logo, New RectangleF(40,40,240,65))
imageShape.Line.FillFormat.FillType = FillFormatType.None
ppt.SaveToFile("result.pptx", FileFormat.Pptx2013)

Spire.Presentation supports to align text vertically in a table cell on the presentation slides. In this article, we will show you how to use C# to align the text in table cell and set the text direction. Firstly, view the screenshot on Microsoft PowerPoint of the vertical alignment and the text direction:

Vertically align the text in 

table cell

Detail steps:

Step 1: Create a new PowerPoint document and load the sample document from file.

Presentation ppt = new Presentation();
ppt.LoadFromFile("Sample1.pptx",FileFormat.Pptx2010);

Step 2: Get the table shape from the first presentation slide.

ITable table = null;
foreach (IShape shape in ppt.Slides[0].Shapes)
{
    if (shape is ITable)
    {
        table = (ITable)shape;

Step 3: Aligning the text vertically and set the text direction.

table[i, 0].TextAnchorType = TextAnchorType.Center;          
table[i, 0].VerticalTextType = VerticalTextType.Vertical270;

table[i, 1].TextAnchorType = TextAnchorType.Center;
table[i, 1].VerticalTextType = VerticalTextType.Horizontal;

table[i, 2].TextAnchorType = TextAnchorType.Center;
table[i, 2].VerticalTextType = VerticalTextType.Vertical;

Step 4: Save the document to file.

ppt.SaveToFile("Result.pptx", FileFormat.Pptx2010);

Effective screenshot after set the vertical alignment and the text direction:

Vertically align the text in 

table cell

Full codes of vertical align the text and set the text direction.:

Presentation ppt = new Presentation();

ppt.LoadFromFile("Sample1.pptx",FileFormat.Pptx2010);

ITable table = null;
foreach (IShape shape in ppt.Slides[0].Shapes)
{
    if (shape is ITable)
    {
        table = (ITable)shape;

        for (int i = 0; i < table.ColumnsList.Count; i++)
        {
            table[i, 0].TextAnchorType = TextAnchorType.Center;                         
            table[i, 0].VerticalTextType = VerticalTextType.Vertical270;


            table[i, 1].TextAnchorType = TextAnchorType.Center;
            table[i, 1].VerticalTextType = VerticalTextType.Horizontal;

            table[i, 2].TextAnchorType = TextAnchorType.Center;
            table[i, 2].VerticalTextType = VerticalTextType.Vertical;
            
        }
    }
}

ppt.SaveToFile("Result.pptx", FileFormat.Pptx2010);

With Spire.Presentation, we can programmatically set the Alternative Text for PowerPoint shapes along with get the Alternative Text of PowerPoint shapes. This article demonstrates how we can use Spire.Presentation to accomplish this function.

Detail steps:

Step 1: Instantiate a Presentation object and load the PowerPoint file.

Presentation ppt = new Presentation();
ppt.LoadFromFile("Input.pptx");

Step 2: Get the first slide.

ISlide slide = ppt.Slides[0];

Step 3: Set or get the alternative text of the first Shape in the slide.

//Set the alternative text (title and description)
slide.Shapes[0].AlternativeTitle = "Rectangle";
slide.Shapes[0].AlternativeText = "This is a Rectangle";

//Get the alternative text (title and description)
//string title = slide.Shapes[0].AlternativeTitle;
//string description = slide.Shapes[0].AlternativeText;

Step 4: Save the file.

ppt.SaveToFile("Output.pptx", FileFormat.Pptx2013);

Screenshot after setting alternative text:

Set and Get Alternative Text 

(Title and Description) of PowerPoint Shapes in C#

Full code:

using Spire.Presentation;

namespace Set_and_Get_Alternative_Text_of_Shape
{
    class Program
    {
        static void Main(string[] args)
        {
            //Instantiate a Presentation object
            Presentation ppt = new Presentation();
            //Load the PowerPoint file
            ppt.LoadFromFile("Input.pptx");

            //Get the first slide
            ISlide slide = ppt.Slides[0];

            //Set the alternative text (title and description)
            slide.Shapes[0].AlternativeTitle = "Rectangle";
            slide.Shapes[0].AlternativeText = "This is a Rectangle";

            //Get the alternative text (title and description)
            //string title = slide.Shapes[0].AlternativeTitle;
            //string description = slide.Shapes[0].AlternativeText;

            //Save the file
            ppt.SaveToFile("Output.pptx", FileFormat.Pptx2013);
        }
    }
}

Text watermark and image watermark are two kinds of watermarks in Word document. The text watermark always shows some additional but related information to the word context. While image watermark is used to make the Word document be more attractive. This section will demonstrate how to use Spire.Doc to add text watermark and image watermark to Word document in C#.

Add Image Watermark in C#:

//create a new instance of Document and load the document from file.
Document doc = new Document();
doc.LoadFromFile("Sample.docx", FileFormat.Docx2013);

//create a new instance of the PictureWatermark and load the picture from file.
PictureWatermark picture = new PictureWatermark();
picture.Picture = System.Drawing.Image.FromFile("logo.png");

//set the image watermark scaling and Washout property
picture.Scaling = 20;
picture.IsWashout = false;

//add the picture watermark
doc.Watermark = picture;
                   
//save the document to file
doc.SaveToFile("ImageWatermark.docx", FileFormat.Docx2013);

Add text watermark and image watermark to word document in C#

Add Text Watermark in C#::

//create a new instance of Document and load the document from file.
Document doc = new Document();
doc.LoadFromFile("Sample.docx", FileFormat.Docx2013);

//create a new instance of the TextWatermark 
TextWatermark txtWatermark = new TextWatermark();

//set the text watermark with text string, font, color and layout.
txtWatermark.Text = "Confidential";
txtWatermark.FontSize = 45;
txtWatermark.Color = Color.Green;
txtWatermark.Layout = WatermarkLayout.Diagonal;

//add the text watermark
doc.Watermark = txtWatermark;

//save the file.
doc.SaveToFile("TextWatermark.docx", FileFormat.Docx2013);

Add text watermark and image watermark to word document in C#

Page 1 of 7