Friday, 13 December 2019 07:34

Convert Image to PDF in Java

Spire.PDF for Java supports converting multiple image formats such as BMP, JPEG, GIF, PNG, TIFF and ICO to PDF. The following example will show you how to convert an image to PDF using Spire.PDF for Java.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfImage;

public class ImageToPDF {
    public static void main(String[] args){
        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();
        //Add a page
        PdfPageBase page = pdf.getPages().add();

        //Load the image
        PdfImage image = PdfImage.fromFile("Hydrangeas.jpg");

        //Draw the image to the specific rectangular area of the page 
        double widthFitRate = image.getPhysicalDimension().getWidth() / page.getCanvas().getClientSize().getWidth();
        double heightFitRate = image.getPhysicalDimension().getHeight() / page.getCanvas().getClientSize().getHeight();
        double fitRate = Math.max(widthFitRate, heightFitRate);
        double fitWidth = image.getPhysicalDimension().getWidth() / fitRate;
        double fitHeight = image.getPhysicalDimension().getHeight() / fitRate;
        page.getCanvas().drawImage(image, new Rectangle2D.Double(0, 0, fitWidth, fitHeight));

        //Save the resultant document
        pdf.saveToFile("ConvertImageToPDF.pdf");
    }
}

Convert Image to PDF in Java

This article demonstrates how to split a PowerPoint document into multiple individual slides using Spire.Presentation for Java.

import com.spire.presentation.FileFormat;
import com.spire.presentation.Presentation;

public class SplitPowerPoint {

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

        //Load the sample PowerPoint file
        Presentation ppt = new Presentation();
        ppt.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pptx");

        //Loop through the slides
        for (int i = 0; i < ppt.getSlides().getCount(); i++)
        {
            //Create an instance of Presentation class
            Presentation newppt = new Presentation();

            //Remove the default slide
            newppt.getSlides().removeAt(0);

            //Select a slide from the source file and append it to the new document
            newppt.getSlides().append(ppt.getSlides().get(i));

            //Save to file
            newppt.saveToFile(String.format("output/result-%d.pptx",i), FileFormat.PPTX_2013);
        }
    }
}

Output:

Split PowerPoint Document into Individual Slides in Java

Wednesday, 11 December 2019 08:23

Print PDF pages to booklet in C#

Booklets are usually used when we print huge PDF files. It saves paper and make the pages tidy. Starts from Spire.PDF V5.12.3, Spire.PDF supports to print the PDF pages to booklet directly. This article demonstrates how to print PDF pages to booklet in C#.

using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.General;
using Spire.Pdf.Print;

namespace PDFPrintBookLet
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the sample document
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile("Sample.pdf");

            //Set booklet layout when print the pdf files
            PdfBookletSubsetMode bookletSubset = PdfBookletSubsetMode.BothSides;
            PdfBookletBindingMode bookletBinding = PdfBookletBindingMode.Left;
            doc.PrintSettings.SelectBookletLayout(bookletSubset, bookletBinding);

            //Print PDF to virtual printer
            doc.PrintSettings.PrinterName = "Microsoft XPS Document Writer";
            doc.PrintSettings.PrintToFile("XpsBooklet.xps");
            doc.Print();  
        }
    }
}

Screenshot after printing to XPS:

Print PDF pages to booklet in C#

Spire.Presentation 4.11 and the later versions provide the following methods to replace text in PowerPoint document:

ReplaceFirstText(string matchedString, string newValue, bool caseSensitive): replace the first occurrence of searched text only.

ReplaceAllText(string matchedString, string newValue, bool caseSensitive): replace all the occurrences of searched text.

In the below examples, we will show you how to use the above methods to replace text in a PowerPoint document.

Replace the first occurrence of searched text only

using Spire.Presentation;

namespace ReplaceFirstText
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Presentation instance
            Presentation ppt = new Presentation();
            //Load the PowerPoint document
            ppt.LoadFromFile("Input.pptx");

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

            //Replace the first occurrence of “Spire.Presentation” with “New Text” by using ReplaceFirstText method
            slide.ReplaceFirstText("Spire.Presentation", "New Text", false);

            //Save the resultant document
            ppt.SaveToFile("RplaceFirstText.pptx", FileFormat.Pptx2013);
        }
    }
}

New Method to Replace Text in PowerPoint in C#

Replace all the occurrences of searched text

using Spire.Presentation;

namespace ReplaceAllText
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Presentation instance
            Presentation ppt = new Presentation();
            //Load the PowerPoint document
            ppt.LoadFromFile("Input.pptx");

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

            //Replace all the occurrences of “Spire.Presentation” with “New Text” by using ReplaceAllText method
            slide.ReplaceAllText("Spire.Presentation", "New Text", false);

            //Save the resultant document
            ppt.SaveToFile("RplaceAllText.pptx", FileFormat.Pptx2013);
        }
    }
}

New Method to Replace Text in PowerPoint in C#

Wednesday, 04 December 2019 03:42

Highlight Text in PowerPoint in C#

This article demonstrates how to highlight the specific text within a PowerPoint document by using Spire.Presentation for .NET.

using Spire.Presentation;
using System.Drawing;

namespace HighlightTextInPPT
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the sample PowerPoint file
            Presentation presentation = new Presentation();
            presentation.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pptx");

            //Loop through the slides
            for (int i = 0; i < presentation.Slides.Count; i++)
            {
                //Get the specific slide
                ISlide slide = presentation.Slides[i];

                //Loop through the shapes
                for (int j = 0; j < slide.Shapes.Count; j++)
                {
                    if (slide.Shapes[j] is IAutoShape)
                    {
                        //Get the specific shape
                        IAutoShape shape = slide.Shapes[j] as IAutoShape;

                        //Initialize an object of TextHighLightingOptions
                        TextHighLightingOptions options = new TextHighLightingOptions();
                        options.CaseSensitive = true;
                        options.WholeWordsOnly = true;

                        //Highligh the specific text within the shape with color
                        shape.TextFrame.HighLightText("Spire.Presentation", Color.LightYellow, options);
                    }
                   
                }
            }

            //Save to file
            presentation.SaveToFile("Highlight Text.pptx", FileFormat.Pptx2013);
        }
    }
}

Highlight Text in PowerPoint in C#

Table of contents (TOC) makes the PDF documents more accessible and easier to navigate, especially for large files. This article demonstrates how to create table of contents (TOC) for a PDF document using Spire.PDF for Java.

import com.spire.pdf.*;
import com.spire.pdf.actions.PdfGoToAction;
import com.spire.pdf.annotations.*;
import com.spire.pdf.general.PdfDestination;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.*;

public class TableOfContent {
    public static void main(String[] args) throws Exception
    {
        //load PDF file
        PdfDocument doc = new PdfDocument("sample.pdf");
        int pageCount = doc.getPages().getCount();
        //Insert a new page as the first page to draw table of content
        PdfPageBase tocPage = doc.getPages().insert(0);
        //set title
        String title = "Table Of Contents";
        PdfTrueTypeFont titleFont = new PdfTrueTypeFont(new Font("Arial",  Font.BOLD,20));
        PdfStringFormat centerAlignment = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
        Point2D location = new Point2D.Float((float) tocPage.getCanvas().getClientSize().getWidth() / 2, (float) titleFont.measureString(title).getHeight());
        tocPage.getCanvas().drawString(title, titleFont, PdfBrushes.getCornflowerBlue(), location, centerAlignment);
        //draw TOC text
        PdfTrueTypeFont titlesFont = new PdfTrueTypeFont(new Font("Arial", Font.PLAIN,14));
        String[] titles = new String[pageCount];
        for (int i = 0; i < titles.length; i++) {
            titles[i] = String.format("page%1$s", i + 1);
        }
        float y = (float)titleFont.measureString(title).getHeight() + 10;
        float x = 0;
        for (int i = 1; i <= pageCount; i++) {
            String text = titles[i - 1];
            Dimension2D titleSize = titlesFont.measureString(text);
            PdfPageBase navigatedPage = doc.getPages().get(i);
            String pageNumText = (String.valueOf(i+1));
            Dimension2D pageNumTextSize = titlesFont.measureString(pageNumText);
            tocPage.getCanvas().drawString(text, titlesFont, PdfBrushes.getCadetBlue(), 0, y);
            float dotLocation = (float)titleSize.getWidth() + 2 + x;
            float pageNumlocation = (float)(tocPage.getCanvas().getClientSize().getWidth() - pageNumTextSize.getWidth());
            for (float j = dotLocation; j < pageNumlocation; j++) {
                if (dotLocation >= pageNumlocation) {
                    break;
                }
                tocPage.getCanvas().drawString(".", titlesFont, PdfBrushes.getGray(), dotLocation, y);
                dotLocation += 3;
            }
            tocPage.getCanvas().drawString(pageNumText, titlesFont, PdfBrushes.getCadetBlue(), pageNumlocation, y);
            //add TOC action
            Rectangle2D titleBounds = new Rectangle2D.Float(0,y,(float)tocPage.getCanvas().getClientSize().getWidth(),(float)titleSize.getHeight());
            PdfDestination Dest = new PdfDestination(navigatedPage, new Point2D.Float(-doc.getPageSettings().getMargins().getTop(), -doc.getPageSettings().getMargins().getLeft()));
            PdfActionAnnotation action = new PdfActionAnnotation(titleBounds, new PdfGoToAction(Dest));
            action.setBorder(new PdfAnnotationBorder(0));
            ((PdfNewPage) ((tocPage instanceof PdfNewPage) ? tocPage : null)).getAnnotations().add(action);
            y += titleSize.getHeight() + 10;
        }

        //save the resultant file
        doc.saveToFile("addTableOfContent.pdf");
        doc.close();
    }
}

Output:

Create Table of Contents (TOC) in PDF in Java

Thursday, 28 November 2019 06:48

Java set table style for the PowerPoint table

With Spire.Presentation for Java, we can format a table by applying preset table styles. This article will demonstrate how to apply predefined styles to a table on presentation slides.

Firstly, view the table on the PowerPoint document:

Java set table style for the PowerPoint table

import com.spire.presentation.ITable;
import com.spire.presentation.Presentation;
import com.spire.presentation.FileFormat;
import com.spire.presentation.TableStylePreset;

public class SetTableStyle {
    public static void main(String[] args) throws Exception {

        //Create a PPT document and load file
        Presentation presentation = new Presentation();
        presentation.loadFromFile("Sample.pptx");

        ITable table = null;

        for (Object shape : presentation.getSlides().get(0).getShapes()) {
            if (shape instanceof ITable) {
                table = (ITable) shape;
                //Set the table style from TableStylePreset and apply it to selected table
                table.setStylePreset(TableStylePreset.MEDIUM_STYLE_1_ACCENT_2);
            }
        }
        //Save the file
       presentation.saveToFile("SetTableStyle.pptx", FileFormat.PPTX_2010);

    }
}

Effective screenshot after updating the table style:

Java set table style for the PowerPoint table

Wednesday, 27 November 2019 03:29

Duplicate a Page in PDF in Java

This article demonstrates how to duplicate a page within a PDF document using Spire.PDF for Java.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfMargins;
import com.spire.pdf.graphics.PdfTemplate;

import java.awt.geom.Dimension2D;
import java.awt.geom.Point2D;

public class DuplicatePage {

    public static void main(String[] args) {

        //Load a sample PDF document
        PdfDocument pdf = new PdfDocument("C:\\Users\\Administrator\\Desktop\\original.pdf");

        //Get the first page
        PdfPageBase page = pdf.getPages().get(0);

        //Get the page size
        Dimension2D size = page.getActualSize();

        //Create a template based on the page
        PdfTemplate template = page.createTemplate();

        for (int i = 0; i < 10; i++) {

            //Add a new page to the document
            page = pdf.getPages().add(size, new PdfMargins(0));

            //Draw template on the new page
            page.getCanvas().drawTemplate(template, new Point2D.Float(0, 0));
        }

        //Save the file
        pdf.saveToFile("output/DuplicatePage.pdf");
    }
}

Duplicate a Page in PDF in Java

Wednesday, 20 November 2019 07:45

Replace Text with Image in Word in Java

This article demonstrates how to replace selected text in a Word document with an image using Spire.Doc for Java.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;

public class ReplaceTextWithImage {

    public static void main(String[] args) {

        //Load a sample Word file
        Document document = new Document();
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

        //Find the string 'E-iceblue' in the document
        TextSelection[] selections = document.findAllString("E-iceblue", true, true);

        //Replace the string with an image
        int index = 0;
        TextRange range = null;
        for (Object obj : selections) {

            TextSelection textSelection = (TextSelection)obj;
            DocPicture pic = new DocPicture(document);
            pic.loadImage("C:\\Users\\Administrator\\Desktop\\e-iceblue-logo.png");
            range = textSelection.getAsOneRange();
            index = range.getOwnerParagraph().getChildObjects().indexOf(range);
            range.getOwnerParagraph().getChildObjects().insert(index,pic);
            range.getOwnerParagraph().getChildObjects().remove(range);
        }

        //Save the document
        document.saveToFile("output/ReplaceTextWithImage.docx", FileFormat.Docx_2013);
    }
}

Replace Text with Image in Word in Java

Wednesday, 20 November 2019 03:34

Add Trendline to Chart in PowerPoint in Java

A trendline is a line superimposed on a chart revealing the overall direction of the data. Spire.Presentation for Java supports adding six different types of trendlines to chart, i.e. linear, logarithmic, polynomial, power, exponential and moving average.

The below example demonstrates how to use Spire.Presentation for Java to add a linear trendline to a chart.

import com.spire.presentation.FileFormat;
import com.spire.presentation.ISlide;
import com.spire.presentation.Presentation;
import com.spire.presentation.charts.IChart;
import com.spire.presentation.charts.ITrendlines;
import com.spire.presentation.charts.TrendlineSimpleType;

public class AddTrendlineToChart {
    public static void main(String[] args) throws Exception {
        //create a Presentation instance
        Presentation ppt = new Presentation();
        //load the PowerPoint document
        ppt.loadFromFile("Chart.pptx");

        //get the first slide
        ISlide slide = ppt.getSlides().get(0);
        //get the chart on the slide
        IChart chart = (IChart)slide.getShapes().get(0);

        //add a linear trendline to the first series of the chart
        ITrendlines trendLine = chart.getSeries().get(0).addTrendLine(TrendlineSimpleType.LINEAR);
        //display equation
        trendLine.setdisplayEquation(true);

        //save the resultant document
        ppt.saveToFile("AddTrendline.pptx", FileFormat.PPTX_2013);
    }
}

Output:

Add Trendline to Chart in PowerPoint in Java

Page 8 of 121