How to set dimensions for png converted from xps document

Hello,

I am converting XPS document to png and I want to customize the size of png generated. How can I set the dimensions to png using aspose-page?

@aakanksha76

To customize the size of a PNG generated from an XPS document using Aspose.Page, you can set the dimensions by configuring the ImageDevice and PngSaveOptions. Below is an example of how to achieve this:

import com.aspose.xps.XpsDocument;
import com.aspose.xps.rendering.ImageDevice;
import com.aspose.xps.rendering.PngSaveOptions;
import java.io.FileOutputStream;
import java.awt.Dimension;

public class XpsToPngConverter {
    public static void main(String[] args) {
        String sourceFilePath = "path/to/your/input.xps";
        String outputFilePath = "path/to/your/output.png";

        // Create an instance of XpsDocument
        XpsDocument document = new XpsDocument(sourceFilePath);
        
        // Create PNG save options
        PngSaveOptions pngSaveOptions = new PngSaveOptions();
        pngSaveOptions.setSmoothingMode(SmoothingMode.HighQuality);
        pngSaveOptions.setResolution(300); // Set the desired resolution
        pngSaveOptions.setPageNumbers(new int[] { 1 }); // Specify the page number to convert

        // Create rendering device for XPS format
        ImageDevice device = new ImageDevice();
        device.setSize(new Dimension(216, 288)); // Set the desired dimensions for the output PNG

        // Save XPS as PNG
        document.save(device, pngSaveOptions);

        // Iterate through document partitions and write the output
        for (int i = 0; i < 1; i++) { // Assuming you are converting the first partition
            for (int j = 0; j < device.getResult()[i].length; j++) {
                try (FileOutputStream imageStream = new FileOutputStream(outputFilePath)) {
                    // Write image to output stream
                    imageStream.write(device.getResult()[i][j], 0, device.getResult()[i][j].length);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

In this code snippet:

  • You create an instance of XpsDocument with the path to your XPS file.
  • You configure PngSaveOptions to set the resolution and specify which page to convert.
  • The ImageDevice is used to set the desired dimensions for the output PNG.
  • Finally, the document is saved as a PNG, and the resulting images are written to the specified output file.

Make sure to adjust the dimensions in device.setSize(new Dimension(216, 288)); to your desired width and height. This should help you generate a PNG with the specified dimensions from your XPS document.