Tuesday, 10 August 2021 07:43

Embed a Zip File in PowerPoint in Java

This article shows you how to embed a zip file as an OLE object in a PowerPoint document using Spire.Presentation for Java.

import com.spire.presentation.*;
import com.spire.presentation.drawing.IImageData;

import javax.imageio.ImageIO;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;

public class InsertZip {

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

        //Create a Presentation object
        Presentation presentation = new Presentation();
        presentation.getSlideSize().setType(SlideSizeType.SCREEN_16_X_9);

        //Get the first slide
        ISlide slide = presentation.getSlides().get(0);

        //Load a zip file and convert it to a byte[] object
        String filePath = "C:\\Users\\Administrator\\Desktop\\sample.zip";
        File zipFile = new File(filePath);
        FileInputStream inputStream = new FileInputStream(zipFile);
        byte[] data = new byte[(int) zipFile.length()];
        inputStream.read(data, 0, data.length);

        //Load an image file as the display icon
        File file = new File("C:\\Users\\Administrator\\Desktop\\winrar-icon.png");
        BufferedImage image = ImageIO.read(file);
        IImageData oleImage = presentation.getImages().append(image);
        
        //Insert the zip file as an OLE object to the first slide
        Rectangle2D rect = new Rectangle2D.Float(60, 60, image.getWidth(), image.getHeight());
        IOleObject oleObject = slide.getShapes().appendOleObject("zip", data, rect);
        oleObject.getSubstituteImagePictureFillFormat().getPicture().setEmbedImage(oleImage);
        oleObject.setProgId("Package");
        
        //Save to file
        presentation.saveToFile("output/InsertZip.pptx", FileFormat.PPTX_2013);
    }
}

 

Embed a Zip File in PowerPoint in Java

This article demonstrates how to convert shapes and SmartArt graphics in Excel to Image in C# using Spire.XLS for .NET.

The input Excel file:

Convert Shapes and SmartArt in Excel to Image in C#, VB.NET

C#
using Spire.Xls;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;

namespace Convert_Shapes_and_SmartArt_to_Image
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook object
            Workbook workbook = new Workbook();
            //Load the Excel file
            workbook.LoadFromFile("Sample.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Create a SaveShapeTypeOption object
            SaveShapeTypeOption shapelist = new SaveShapeTypeOption();
            //Save shapes and SmartArt graphics in the worksheet to images
            List images = sheet.SaveShapesToImage(shapelist);

            //Save images to file
            int index = 0;
            foreach (Image img in images)
            {
                img.Save("Image/" + "toImage" + index + ".Png", ImageFormat.Png);
                index++;
            }
        }
    }
}
VB.NET
Imports Spire.Xls
Imports System.Collections.Generic
Imports System.Drawing.Imaging

Namespace Convert_Shapes_and_SmartArt_to_Image
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Workbook object
            Dim workbook As Workbook = New Workbook()
            'Load the Excel file
            workbook.LoadFromFile("Sample.xlsx")

            'Get the first worksheet
            Dim sheet As Worksheet = workbook.Worksheets(0)

            'Create a SaveShapeTypeOption object
            Dim shapelist As SaveShapeTypeOption = New SaveShapeTypeOption()
            'Save shapes and SmartArt graphics in the worksheet to images
            Dim images As List(Of Bitmap) = sheet.SaveShapesToImage(shapelist)

            'Save images to file
            Dim index As Integer = 0

            For Each img As Image In images
                img.Save("Image/" & "toImage" & index & ".Png", ImageFormat.Png)
                index += 1
            Next
        End Sub
    End Class
End Namespace

Converted images:

Convert Shapes and SmartArt in Excel to Image in C#, VB.NET

This article demonstrates how to verify if a Word document is password protected or not using Spire.Doc for Java.

The following image shows that the input Word document is protected with password:

Verify If a Word Document is Password Protected in Java

import com.spire.doc.Document;

public class DetectIfWordIsPasswordProtected {
    public static void main(String []args){
        //Detect if the Word document is password protected
        boolean isPasswordProtected = Document.isPassWordProtected("C:\\Users\\Administrator\\Desktop\\Sample.docx");
        if(isPasswordProtected)
        {
            System.out.println("The document is password protected.");
        }
        else
        {
            System.out.println("The document is not password protected.");
        }
    }
}

Output:

Verify If a Word Document is Password Protected in Java

Tuesday, 03 August 2021 08:35

Rearrange PDF Pages in Java

This article demonstrates how to change page order in a PDF document using Spire.PDF for Java.

import com.spire.pdf.PdfDocument;

public class RearrangePages {

    public static void main(String[] args) {

        //Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        //Load the sample PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");

        //Rearrange pages by setting a new page order
        doc.getPages().reArrange(new int[]{1, 0, 2, 3});

        //Save to file
        doc.saveToFile("output/ChangeOrder.pdf");
        doc.close();
    }
}

Rearrange PDF Pages in Java

This article demonstrates how to compress high-resolution images of a PDF document using Spire.PDF for Java. Images in low-resolution will not be compressed anymore.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.exporting.PdfImageInfo;

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

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

        //Set IncrementalUpdate to false
        doc.getFileInfo().setIncrementalUpdate(false);

        //Declare a PdfPageBase variable
        PdfPageBase page;

        //Loop through the pages 
        for (int i = 0; i < doc.getPages().getCount(); i++) {

            //Get the specific page
            page = doc.getPages().get(i);
            if (page != null) {

                if(page.getImagesInfo() != null){

                    //Loop through the images in the page
                    for (PdfImageInfo info: page.getImagesInfo()) {

                        //Use tryCompressImage method the compress high-resolution images
                        page.tryCompressImage(info.getIndex());
                    }
                }
            }
        }

        //Save to file
        doc.saveToFile("output/Compressed.pdf");
    }
}

Compress High-resolution Images in PDF in Java

This article demonstrates how to detect if a PDF file is a portfolio in Java using Spire.PDF for Java.

The following is the screenshot of the input PDF:

Detect if a PDF File is a Portfolio in Java

import com.spire.pdf.PdfDocument;

public class DetectPortfolio {
    public static void main(String []args){
        //Create a PdfDocument instance
        PdfDocument doc = new PdfDocument();
        //Load the PDF file
        doc.loadFromFile("Portfolio.pdf");

        //Detect if the PDF is a portfolio
        boolean value = doc.isPortfolio();
        if (value)
        {
            System.out.println("The document is a portfolio.");
        }
        else
        {
            System.out.println("The document is not a portfolio.");
        }
    }
}

Output:

Detect if a PDF File is a Portfolio in Java

This article demonstrates how to remove or update hyperlinks in PDF documents using Spire.PDF for Java. When you remove a hyperlink using the method described in this article, the hyperlink appearance will remain unchanged, but the link behind will be deleted.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.annotations.PdfAnnotationCollection;
import com.spire.pdf.annotations.PdfUriAnnotationWidget;

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

        //Create a PdfDocument object
        PdfDocument document = new PdfDocument();

        //Load the sample PDF file
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\Hyperlinks.pdf");

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

        //Get annotation collection
        PdfAnnotationCollection widgetCollection = page.getAnnotationsWidget();

        //Remove the second annotation which is a hyperlink in the document
        widgetCollection.removeAt(1);

        //Get the first url annotation widget
        PdfUriAnnotationWidget uriWidget = (PdfUriAnnotationWidget)widgetCollection.get(0);

        //Reset the url
        uriWidget.setUri("https://www.e-iceblue.com/Introduce/pdf-for-java.html");

        //Save to file
        document.saveToFile("Result.pdf");
    }
}

Remove or Update Hyperlinks in PDF in Java

Comments are used to provide additional information or draw attention to something in the document. Sometimes, the text being commented is also useful, and you may want to extract it for other purposes. In this article, you will learn how to extract the text between two comment marks in a Word document using Spire.Doc for Java.

Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

  • Package Manager
<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>4.11.8</version>
    </dependency>
</dependencies>

Get Text Between Two Comment Marks in Word

To get the text between the start mark (represented by CommentMarkStart class) and the end mark (represented by CommentMarkEnd class), you’ll need to get the indexes of the comment marks. These indexes specify the position of the text being marked in a paragraph. The following are the detailed steps to get text inside two comment marks in a Word document.

  • Create a Document object, and load a sample Word document using Document.loadFromFile() method.
  • Get the first comment using Document.getComments().get() method.
  • Get the start mark and end mark of the comment.
  • Get the start mark's index and the end mark's index in the owner paragraph.
  • Get the text range between the indexes, and then get the text of the text range using TextRage.getText() method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.documents.CommentMark;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.Comment;
import com.spire.doc.fields.TextRange;

public class GetTextInsideCommentMarkers {

    public static void main(String[] args) {

        //Create a Document object
        Document doc = new Document();

        //Load the sample Word document
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx");

        //Get the first comment
        Comment comment = doc.getComments().get(0);

        //Get the start mark and end mark of the comment
        Paragraph para = comment.getOwnerParagraph();
        CommentMark start = comment.getCommentMarkStart();
        CommentMark end = comment.getCommentMarkEnd();

        //Get the start mark’s index and the end mark’s index respectively
        int indexOfStart = para.getChildObjects().indexOf(start);
        int indexOfEnd = para.getChildObjects().indexOf(end);

        //Declare a String variable
        String textMarked = "";

        //Loop through the numbers between two indexes
        for (int i = indexOfStart + 1; i < indexOfEnd; i++) {
            if (para.getChildObjects().get(i) instanceof TextRange) {

                //Get the text range specified by the index
                TextRange range = (TextRange) para.getChildObjects().get(i);

                //Get text from the text range
                textMarked += range.getText();
            }
        }

        //Print out the text being marked
        System.out.println(textMarked);
    }
}

Java: Get Text Between Two Comment Marks in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

This article demonstrates how to embed a timestamp when digitally signing PDF documents using Spire.PDF for Java.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.graphics.*;
import com.spire.pdf.security.GraphicMode;
import com.spire.pdf.security.PdfCertificate;
import com.spire.pdf.security.PdfCertificationFlags;
import com.spire.pdf.security.PdfSignature;

import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

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

        //Load a pdf document
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Introduction.pdf");

        //Load the certificate
        PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\gary.pfx", "e-iceblue");

        //Create a PdfSignature object and specify its position and size
        PdfSignature signature = new PdfSignature(doc, doc.getPages().get(0), cert, "MySignature");
        Rectangle2D rect = new Rectangle2D.Float();
        rect.setFrame(new Point2D.Float((float) doc.getPages().get(0).getActualSize().getWidth() - 220, (float) doc.getPages().get(0).getActualSize().getHeight() - 140), new Dimension(200, 100));
        signature.setBounds(rect);

        //Set the graphics mode
        signature.setGraphicMode(GraphicMode.Sign_Detail);

        //Set the signature content
        signature.setNameLabel("Signer:");
        signature.setName("Gary");
        signature.setContactInfoLabel("ContactInfo:");
        signature.setContactInfo("02881705109");
        signature.setLocationInfoLabel("Location:");
        signature.setLocationInfo("Chengdu");
        signature.setReasonLabel("Reason: ");
        signature.setReason("The certificate of this document");

        //Set the signature font
        signature.setSignDetailsFont(new PdfFont(PdfFontFamily.Helvetica, 10f, PdfFontStyle.Regular));

        //Set the document permission
        signature.setDocumentPermissions(PdfCertificationFlags.Forbid_Changes);
        signature.setCertificated(true);

        //Configure a time stamp server
        String timestampServerUrl = "http://timestamp.digicert.com";
        signature.configureTimestamp(timestampServerUrl);

        //Save to file
        doc.saveToFile("Timestamp.pdf");
        doc.close();
    }
}

Digitally Sign a PDF with a Timestamp in Java

This article demonstrates how to extract files from a PDF portfolio in Java using Spire.PDF for Java.

The input PDF:

Extract Files from PDF Portfolio in Java

import com.spire.pdf.PdfDocument;
import com.spire.pdf.attachments.PdfAttachment;

import java.io.*;

public class ReadPortfolio {
    public static void main(String []args) throws IOException {
        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();
        //Load the PDF file
        pdf.loadFromFile("Portfolio.pdf");

        //Loop through the attachments in the file
        for(PdfAttachment attachment : (Iterable)pdf.getAttachments()){
            //Extract files
            String fileName = attachment.getFileName();
            OutputStream fos = new FileOutputStream("extract/" + fileName);
            fos.write(attachment.getData());
        }
        pdf.dispose();
    }
}

Output:

Extract Files from PDF Portfolio in Java

Page 8 of 143