DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
  • submit to reddit
package ImageToPdf;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URI;

import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.BreakType;
import com.aspose.words.PageSetup;
import com.aspose.words.ConvertUtil;
import com.aspose.words.RelativeHorizontalPosition;
import com.aspose.words.RelativeVerticalPosition;
import com.aspose.words.WrapType;


class Program
{
    public static void main(String[] args) throws Exception
    {
        // Sample infrastructure.
        URI exeDir = Program.class.getResource("").toURI();
        String dataDir = new File(exeDir.resolve("../../Data")) + File.separator;

        convertImageToPdf(dataDir + "Test.jpg", dataDir + "TestJpg Out.pdf");
        convertImageToPdf(dataDir + "Test.png", dataDir + "TestPng Out.pdf");
        convertImageToPdf(dataDir + "Test.bmp", dataDir + "TestBmp Out.pdf");
        convertImageToPdf(dataDir + "Test.gif", dataDir + "TestGif Out.pdf");
    }

    /**
     * Converts an image to PDF using Aspose.Words for Java.
     *
     * @param inputFileName File name of input image file.
     * @param outputFileName Output PDF file name.
     */
    public static void convertImageToPdf(String inputFileName, String outputFileName) throws Exception
    {
        // Create Aspose.Words.Document and DocumentBuilder.
        // The builder makes it simple to add content to the document.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);

        // Load images from the disk using the approriate reader.
        // The file formats that can be loaded depends on the image readers available on the machine.
        ImageInputStream iis = ImageIO.createImageInputStream(new File(inputFileName));
        ImageReader reader = ImageIO.getImageReaders(iis).next();
        reader.setInput(iis, false);

        try
        {
            // Get the number of frames in the image.
            int framesCount = reader.getNumImages(true);

            // Loop through all frames.
            for (int frameIdx = 0; frameIdx < framesCount; frameIdx++)
            {
                // Insert a section break before each new page, in case of a multi-frame image.
                if (frameIdx != 0)
                    builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);

                // Select active frame.
                BufferedImage image = reader.read(frameIdx);

                // We want the size of the page to be the same as the size of the image.
                // Convert pixels to points to size the page to the actual image size.
                PageSetup ps = builder.getPageSetup();

                ps.setPageWidth(ConvertUtil.pixelToPoint(image.getWidth()));
                ps.setPageHeight(ConvertUtil.pixelToPoint(image.getHeight()));

                // Insert the image into the document and position it at the top left corner of the page.
                builder.insertImage(
                    image,
                    RelativeHorizontalPosition.PAGE,
                    0,
                    RelativeVerticalPosition.PAGE,
                    0,
                    ps.getPageWidth(),
                    ps.getPageHeight(),
                    WrapType.NONE);
            }
        }

        finally {
            if (iis != null) {
                iis.close();
                reader.dispose();
            }
        }

        // Save the document to PDF.
        doc.save(outputFileName);
    }
} 

//Converts large size image into a PDF document

//When the size of image is bigger than max allowed size of MS Word page, an exception is thrown or image is not visible in output document. The measurement for images must be between 0 and 55.88 cm (55.88 cm = 1584 points). In this case, use the following code example.
package ImageToPdf;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URI;

import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.BreakType;
import com.aspose.words.PageSetup;
import com.aspose.words.ConvertUtil;
import com.aspose.words.RelativeHorizontalPosition;
import com.aspose.words.RelativeVerticalPosition;
import com.aspose.words.WrapType;


class Program
{
    public static void main(String[] args) throws Exception
    {
        // Sample infrastructure.
        URI exeDir = Program.class.getResource("").toURI();
        String dataDir = new File(exeDir.resolve("../../Data")) + File.separator;

        convertImageToPdf(dataDir + "Test.jpg", dataDir + "TestJpg Out.pdf");
        convertImageToPdf(dataDir + "Test.png", dataDir + "TestPng Out.pdf");
        convertImageToPdf(dataDir + "Test.bmp", dataDir + "TestBmp Out.pdf");
        convertImageToPdf(dataDir + "Test.gif", dataDir + "TestGif Out.pdf");
    }

    /**
     * Converts an image to PDF using Aspose.Words for Java.
     *
     * @param inputFileName File name of input image file.
     * @param outputFileName Output PDF file name.
     */
    	public static void convertImageToPdf(String inputFileName, String outputFileName) throws Exception
	{
	    // Create Aspose.Words.Document and DocumentBuilder.
	    // The builder makes it simple to add content to the document.
	    Document doc = new Document();
	    DocumentBuilder builder = new DocumentBuilder(doc);

	    // Load images from the disk using the approriate reader.
	    // The file formats that can be loaded depends on the image readers available on the machine.
	    ImageInputStream iis = ImageIO.createImageInputStream(new File(inputFileName));
	    ImageReader reader = ImageIO.getImageReaders(iis).next();
	    reader.setInput(iis, false);

	    try
	    {
	        // Get the number of frames in the image.
	        int framesCount = reader.getNumImages(true);

	        // Loop through all frames.
	        for (int frameIdx = 0; frameIdx < framesCount; frameIdx++)
	        {
	            // Insert a section break before each new page, in case of a multi-frame image.
	            if (frameIdx != 0)
	                builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);

	            // Select active frame.
	            BufferedImage image = reader.read(frameIdx);

	            // Max page size
	            double maxPageHeight = 1584;
	            double maxPageWidth = 1584;

	            double currentImageHeight = ConvertUtil.pixelToPoint(image.getHeight());
	            double currentImageWidth = ConvertUtil.pixelToPoint(image.getWidth());

	            if (currentImageWidth >= maxPageWidth || currentImageHeight >= maxPageHeight)
	            {

	                // Get max image size.
	            	 double[] size = CalculateImageSize(image, maxPageHeight, maxPageWidth, currentImageHeight, currentImageWidth);
	            	 currentImageWidth = size[0];
	            	 currentImageHeight = size[1];
	            }

	            // We want the size of the page to be the same as the size of the image.
	            // Convert pixels to points to size the page to the actual image size.
	            PageSetup ps = builder.getPageSetup();

	            ps.setPageWidth(currentImageWidth);
	            ps.setPageHeight(currentImageHeight);

	            // Insert the image into the document and position it at the top left corner of the page.
	            Shape shape = builder.insertImage(
	                image,
	                RelativeHorizontalPosition.PAGE,
	                0,
	                RelativeVerticalPosition.PAGE,
	                0,
	                ps.getPageWidth(),
	                ps.getPageHeight(),
	                WrapType.NONE);

	            resizeLargeImage(shape);
	        }
	    }

	    finally {
	        if (iis != null) {
	            iis.close();
	            reader.dispose();
	        }
	    }

	    // Save the document to PDF.
	    doc.save(outputFileName);
	}

	public static double[] CalculateImageSize(BufferedImage img, double containerHeight,  double containerWidth, double targetHeight, double targetWidth) throws Exception {

	 targetHeight = containerHeight;
	 targetWidth = containerWidth;

	  //Get size of an image
	    double imgHeight = ConvertUtil.pixelToPoint(img.getHeight());
	    double imgWidth = ConvertUtil.pixelToPoint(img.getWidth());

	    if (imgHeight < targetHeight && imgWidth < targetWidth)
	    {
	        targetHeight = imgHeight;
	        targetWidth = imgWidth;
	    }
	    else
	    {
	        //Calculate size of an image in the document
	        double ratioWidth = imgWidth / targetWidth;
	        double ratioHeight = imgHeight / targetHeight;
	        if (ratioWidth > ratioHeight)
	            targetHeight = (targetHeight * (ratioHeight / ratioWidth));
	        else
	            targetWidth = (targetWidth * (ratioWidth / ratioHeight));
	    }

	    double[] size = new double[2];

	    size[0] = targetWidth; //width
	    size[1] = targetHeight; //height

	    return(size);
	}

    public static void resizeLargeImage(Shape image) throws Exception
    {
        // Return if this shape is not an image.
        if (!image.hasImage())
            return;

        // Calculate the free space based on an inline or floating image. If inline we must take the page margins into account.
        PageSetup ps = image.getParentParagraph().getParentSection().getPageSetup();
        double freePageWidth = image.isInline() ? ps.getPageWidth() - ps.getLeftMargin() - ps.getRightMargin() : ps.getPageWidth();
        double freePageHeight = image.isInline() ? ps.getPageHeight() - ps.getTopMargin() - ps.getBottomMargin() : ps.getPageHeight();

        // Is one of the sides of this image too big for the page?
        ImageSize size = image.getImageData().getImageSize();
        boolean exceedsMaxPageSize = size.getWidthPoints() > freePageWidth || size.getHeightPoints() > freePageHeight;

        if (exceedsMaxPageSize)
        {
            // Calculate the ratio to fit the page size based on which side is longer.
            boolean widthLonger = (size.getWidthPoints() > size.getHeightPoints());
            double ratio = widthLonger ? freePageWidth / size.getWidthPoints() : freePageHeight / size.getHeightPoints();

            // Set the new size.
            image.setWidth(size.getWidthPoints() * ratio);
            image.setHeight(size.getHeightPoints() * ratio);
        }
    }
}
John Walter11/26/14
5973 views
1 replies

The Best of DZone: Nov. 18 - Nov. 25

If you missed anything on DZone this week, now's your chance to catch up! This week's best include a look at the Java 9 features, the most important skill for software architects, why automation matters, and why iOS developers should still know Objective-C.

John Walter11/26/14
5192 views
0 replies

Dev of the Week: Max Katz

Every week here and in our newsletter, we feature a new developer/blogger from the DZone community to catch up and find out what he or she is working on now and what's coming next. This week we're talking to Max Katz, head of Developer Relations for Appery.io.

Jim Bird11/26/14
6519 views
0 replies

Different Ways of Scaling Agile

The major advantage of Agile at scale isn't the ability to react to continuous changes or even to deliver faster or cheaper. It's knowing sooner whether you should keep going, or if you need to keep going, or if you should stop and do something else instead.

Dave Farley11/26/14
1989 views
0 replies

The Reactive Manifesto

The Reactive Manifesto starts from a simple thought. 21st Century problems are not well-served by 20th Century assumptions of software architecture. The game is moving on!

Rob J Hyndman11/26/14
6738 views
0 replies

Visualization of probabilistic forecasts

Of course, for time series fore­casts I nor­mally show pre­dic­tion inter­vals. I pre­fer to use more than one inter­val at a time because it helps con­vey a lit­tle more infor­ma­tion. The default in the fore­cast pack­age for R is to show both an 80% and a 95% inter­val like this:

Paul Hammant11/26/14
5332 views
0 replies

Strong Argumentative Positions

I have long thought that in debates with colleagues (or clients) over a topic/decision that you disagree on, you should go in with your strongest argument(s) only. If you assemble a list different and weaker reasons why you’re right, and the person in disagreement has any authority over you or guile, they will focus on your weakest arguments until the whole debate times out, or you lose energy to continue.

Joost Van Schaik11/26/14
994 views
0 replies

Executing and Testing Geofencing Background Tasks in Universal Apps

On October 18th the Dutch and Belgian Windows Platform Development communities got together for an event called “Lowlands WPdev 2014”- yours truly was one of the conference organizers, and gave a talk about geofencing.

package com.pky.com;

public class StaticExample {
	public static String company = "Infosys Limited";
	public String name;
	public int id;

	public StaticExample(String name, int id) {
		this.name = name;
		this.id = id;
	}

	public void show() {
		System.out.println("Employee Name :" + name + "\nEmployee Id :" + id
				+ "\nEmployee company :" + company);
	}

	public static void main(String arg[]) {
		StaticExample se = new StaticExample("Pradeep Yadav", 99231);
		se.show();

	}
}


Output :

Employee Name :Pradeep Yadav
Employee Id :99231
Employee company :Infosys Limited
Gil Zilberfeld11/25/14
1797 views
0 replies

How To Make The Best Decisions

We can get better at it, by making more of them. Learning from mistakes and successes. We can also learn from observing how decisions are made in our different circles, and try to learn how to push a decision through or derail one.

Mike Cottmeyer11/25/14
1857 views
0 replies

The Napoleon Corporal

In my previous post, Replacing Backlog Grooming, I wrote about leveraging a Product Owner (PO) Team instead of the “Scrum” team in Progression Workshops (backlog grooming). It doesn’t matter if you’re doing textbook Scrum or something at scale. Your people still need a shared understanding. If not, you’re going to start seeing a lot of delays and a lot of rework.

Nicolas Frankel11/25/14
3883 views
0 replies

From Vaadin to Docker - A Novice's Journey

I’m a huge Vaadin fan and I’ve created a Github workshop I can demo at conferences. Given the current buzz around Docker, I thought that could be a very good way to make the workshop preparation quicker

John Walter11/25/14
4233 views
0 replies

7 Common Mistakes In Go And When To Avoid Them

Not a generic list of programming mistakes, these are the lessons I wish I learned earlier while developing Go. I’ve spent the past two years developing some of the most popular libraries and applications written in Go.

John Walter11/25/14
2890 views
0 replies

ElectroPi - Open Source Home Automation

I found this video earlier and wanted to share it. Connor Nishijima, creator of the ElectroPi, shows off his open source RaspberryPi-based home automation board and software he's written.

Maneesh Joshi11/24/14
3071 views
0 replies

Top 5 Mobile APM Myths: Myths 3-5

Typically, mobile app developers accept some things they feel they can’t change — ratings, end-to-end visibility, user experience, and so on. However, these can all be avoided and under your control with the right mAPM solution to give you the proper insights to give your users a seamless experience.

Eric Minick11/24/14
5062 views
0 replies

DevOps and the Resurrection of QA

A couple years ago I wrote that QA would be a natural mediator for DevOps discussions at it is traditionally between Dev and Ops, understands Dev’s speed and has concern for release quality that Ops respects. Two things had me convinced that this pattern wouldn’t happen.

Benjamin Ball11/24/14
3929 views
1 replies

The Best of the Week (Nov 14): Agile Zone

Make sure you didn't miss anything with this list of the Best of the Week in the Agile Zone (November 14 - November 21). This week's topics include agile transformation in big companies, points of failure, Scrum and Kanban, agile perspective shifts, and replacing backlog grooming.

Maarten Ectors11/24/14
3565 views
0 replies

Internet of Things Challenges and Opportunities

IoT is one of the biggest potential new revenue streams but also one of the most challenging technical problems we have today.

Robert Diana11/23/14
1599 views
0 replies

Geek Reading November 19, 2014

These items are the fruits of those ideas, the items I deemed worthy from my daily reading. These items are a combination of tech business news, development news and programming tools and techniques.

Mark Needham11/23/14
6337 views
0 replies

R: Refactoring to dplyr

I’ve been looking back over some of the early code I wrote using R before I knew about the dplyr library and thought it’d be an interesting exercise to refactor some of the snippets.