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

This article shows how to copy a worksheet from an Excel document to anther by using Spire.XLS for Java.

import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

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

        //Create a Workbook object to load the source document
        Workbook srcWorkbook = new Workbook();
        srcWorkbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\source.xlsx");

        //Get the specific worksheet to copy
        Worksheet originalSheet = srcWorkbook.getWorksheets().get(0);

        //Create another Workbook object to load the destination document
        Workbook destWorkbook = new Workbook();
        destWorkbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\destination.xlsx");

        //Add the copy of selected sheet to destination document
        Worksheet newSheet = destWorkbook.getWorksheets().addCopy(originalSheet);
        newSheet.setName(originalSheet.getName());

        //Copy the theme of source document to destination document
        destWorkbook.copyTheme(srcWorkbook);

        //Save to another file
        destWorkbook.saveToFile("CopySheetBetweenWorkbooks.xlsx");
    }
}

Copy Worksheets from one Workbook to another in Java

This article demonstrates how to repeat table header rows across pages in PDF using Spire.PDF for Java.

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import com.spire.pdf.grid.PdfGrid;
import com.spire.pdf.grid.PdfGridRow;

import java.awt.*;

public class RepeatTableHeaderRow {
    public static void main(String[] args) {
        //Create a new PDF document
        PdfDocument pdf = new PdfDocument();

        //Add a page
        PdfPageBase page = pdf.getPages().add();

        //Instantiate a PdfGrid class object
        PdfGrid grid = new PdfGrid();

        //Set cell padding
        grid.getStyle().setCellPadding(new PdfPaddings(1,1,1,1));

        //Add columns
        grid.getColumns().add(3);

        //Add header rows and table data
        PdfGridRow[] pdfGridRows = grid.getHeaders().add(1);
        for (int i = 0; i < pdfGridRows.length; i++)
        {
            pdfGridRows[i].getStyle().setFont(new PdfTrueTypeFont(new Font("Arial", Font.PLAIN,12), true));//Designate a font
            pdfGridRows[i].getCells().get(0).setValue("NAME");
            pdfGridRows[i].getCells().get(1).setValue("SUBJECT");
            pdfGridRows[i].getCells().get(2).setValue("SCORES");
            pdfGridRows[i].getStyle().setTextBrush(PdfBrushes.getRed());
        }

        //Repeat header rows (when across pages)
        grid.setRepeatHeader(true);

        //Add values to the table
        for (int i = 0; i < 60; i++)
        {
            PdfGridRow row = grid.getRows().add();
            for (int j = 0; j < grid.getColumns().getCount();j++)
            {
                row.getCells().get(j).setValue("(Row " + (i+1) + ", column " + (j+1) + ")");
            }
        }

        // Draw a table in PDF 
        grid.draw(page,0,40);

        //Save the document
        pdf.saveToFile("Result.pdf");
        pdf.dispose();
    }
}

Output

Repeat Table Header Rows across Pages in PDF in Java

This article will demonstrate how to repeat the table’s header row in C#/VB.NET by using Spire.PDF for .NET.

C#
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Grid;
using System.Drawing;

namespace PDFGrid
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a pdf document
            PdfDocument doc = new PdfDocument();

            //Add a page to pdf
            PdfPageBase page = doc.Pages.Add();

            //Create a PdfGrid object
            PdfGrid grid = new PdfGrid();

            //Set the cell padding of the grid
            grid.Style.CellPadding = new PdfPaddings(1, 1, 1, 1);

            //Set the Columns of the grid
            grid.Columns.Add(3);

            //Set the header rows and define the data
            PdfGridRow[] pdfGridRows = grid.Headers.Add(2);
            for (int i = 0; i < pdfGridRows.Length; i++)
            {
                pdfGridRows[i].Style.Font = new PdfTrueTypeFont(new Font("Arial", 11f, FontStyle.Regular), true);
                pdfGridRows[i].Cells[0].Value = "Vendor Name";
                pdfGridRows[i].Cells[1].Value = "Address";
                pdfGridRows[i].Cells[2].Value = "City";
            }

            //Repeat the table header rows if the grid exceed one page
            grid.RepeatHeader = true;


            for (int i = 0; i < 60; i++)
            {
                PdfGridRow row = grid.Rows.Add();

                //Add the data to the table
                for (int j = 0; j < grid.Columns.Count; j++)
                {
                    row.Cells[j].Value = "(Row " + i + ", column " + j + ")";
                }
            }

            //draw grid on the pdf page
            PdfLayoutResult pdfLayoutResult = grid.Draw(page, new PointF(0, 20));
            float y = pdfLayoutResult.Bounds.Y + pdfLayoutResult.Bounds.Height;
            PdfPageBase currentPage = pdfLayoutResult.Page;


            //Save the doucment to file
            doc.SaveToFile("PDFGrid.pdf");

        }
    }
}
VB.NET
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Grid
Imports System.Drawing

Namespace PDFGrid
    
    Class Program
        
        Private Shared Sub Main(ByVal args() As String)
            'Create a pdf document
            Dim doc As PdfDocument = New PdfDocument
            'Add a page to pdf
            Dim page As PdfPageBase = doc.Pages.Add
            'Create a PdfGrid object
            Dim grid As PdfGrid = New PdfGrid
            'Set the cell padding of the grid
            grid.Style.CellPadding = New PdfPaddings(1, 1, 1, 1)
            'Set the Columns of the grid
            grid.Columns.Add(3)
            'Set the header rows and define the data
            Dim pdfGridRows() As PdfGridRow = grid.Headers.Add(2)
            Dim i As Integer = 0
            Do While (i < pdfGridRows.Length)
                pdfGridRows(i).Style.Font = New PdfTrueTypeFont(New Font("Arial", 11!, FontStyle.Regular), true)
                pdfGridRows(i).Cells(0).Value = "Vendor Name"
                pdfGridRows(i).Cells(1).Value = "Address"
                pdfGridRows(i).Cells(2).Value = "City"
                i = (i + 1)
            Loop
            
            'Repeat the table header rows if the grid exceed one page
            grid.RepeatHeader = true
            Dim i As Integer = 0
            Do While (i < 60)
                Dim row As PdfGridRow = grid.Rows.Add
                'Add the data to the table
                Dim j As Integer = 0
                Do While (j < grid.Columns.Count)
                    row.Cells(j).Value = ("(Row "  _
                                + (i + (", column "  _
                                + (j + ")"))))
                    j = (j + 1)
                Loop
                
                i = (i + 1)
            Loop
            
            'draw grid on the pdf page
            Dim pdfLayoutResult As PdfLayoutResult = grid.Draw(page, New PointF(0, 20))
            Dim y As Single = (pdfLayoutResult.Bounds.Y + pdfLayoutResult.Bounds.Height)
            Dim currentPage As PdfPageBase = pdfLayoutResult.Page
            'Save the doucment to file
            doc.SaveToFile("PDFGrid.pdf")
        End Sub
    End Class
End Namespace

Effective screenshot of repeating the table's header row:

Repeat the header rows in PDF table in C#, VB.NET

This article shows you how to duplicate a worksheet inside a workbook using Spire.XLS for Java.

import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

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

        //Create a Workbook object
        Workbook workbook = new Workbook();

        //Load the sample Excel file
        workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.xlsx");

        //Get the first worksheet
        Worksheet originalSheet = workbook.getWorksheets().get(0);

        //Add a new worksheet
        Worksheet newSheet = workbook.getWorksheets().add(originalSheet.getName()+" - Copy");

        //Copy the worksheet to new sheet
        newSheet.copyFrom(originalSheet);

        //Save to file
        workbook.saveToFile("DuplicateSheet.xlsx");
    }
}

Duplicate Worksheets within a Workbook in Java

Monday, 05 July 2021 05:22

Create PDF Portfolio in Java

When creating a PDF portfolio, Spire.PDF for Java allows adding files or folders to the portfolio. In the following examples, you will see how to create a portfolio and add files/folders to it.

Create portfolio and add files

import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;

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

        String[] files = new String[] { "sample.pdf", "sample.docx", "sample.xlsx","sample.pptx","image.jpg" };

        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();

        for (int i = 0; i < files.length; i++)
        {
            //Create a PDF Portfolio and add files to it
            pdf.getCollection().addFile(files[i]);
        }
        
        //Save the result file
        pdf.saveToFile("PortfolioWithFiles.pdf", FileFormat.PDF);
        pdf.dispose();
    }
}

Output:

Create PDF Portfolio in Java

Create portfolio and add folders

import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.collections.PdfFolder;

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

        String[] files = new String[] { "sample.pdf", "sample.docx", "sample.xlsx","sample.pptx","image.jpg" };

        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();

        for (int i = 0; i < files.length; i++)
        {
            //Create a portfolio and add folders to it
            PdfFolder folder = pdf.getCollection().getFolders().createSubfolder("folder" + i);
            folder.addFile(files[i]);
        }

        //Save the result file
        pdf.saveToFile("PortfolioWithFolders.pdf", FileFormat.PDF);
        pdf.dispose();
    }
}

Output:

Create PDF Portfolio in Java

In this tutorial, we are going to introduce how to invisiblize the textual data in the middle of creating a Barcode&QR code using Spire.Barcode for Java and its settings.setShowText(false); method.

Invisiblize the Textual Data When Creating a Barcode

import com.spire.barcode.BarCodeGenerator;
import com.spire.barcode.BarCodeType;
import com.spire.barcode.BarcodeSettings;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class CreateBarcode {
    public static void main(String[] args) throws IOException {
        BarcodeSettings settings = new BarcodeSettings();//Instantiate BarcodeSettings object
        settings.setType(BarCodeType.Codabar);//Set the Barcode type
        settings.setData("123456789");//Set the Barcode data
        settings.setShowText(false);//Make the textual data invisible
        settings.setShowTextOnBottom(true);//Make the textual data visible at the bottom of the Barcode
        settings.setX(0.8f);//Set width for the black and white stripes
        settings.setImageHeight(50);//Set height for the created Barcode image
        settings.setImageWidth(70);//Set width for the created Barcode image
        settings.hasBorder(true);//Make the border visible
        settings.setBorderColor(new Color(135,206,250));//Set the border color
        settings.setBorderWidth(1);//Set the border width
        settings.setBackColor(new Color(240,255,255));//Set background color for the Barcode

        BarCodeGenerator barCodeGenerator = new BarCodeGenerator(settings);//Instantiage BarCodeGenerator object
        BufferedImage bufferedImage = barCodeGenerator.generateImage();//Generate image data based on settings and save it to BufferedImage instance
        ImageIO.write(bufferedImage, "png", new File("Codabar.png"));//Save the Barcode as PNG
    }
}

Output

Invisiblize Textual Data When Creating Barcode&QR code in Java

Invisiblize the Textual Data When Creating a QR code

import com.spire.barcode.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

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

               BarcodeSettings settings = new BarcodeSettings();//Instantiate BarcodeSettings object
        settings.setType(BarCodeType.QR_Code);//Set Barcode type as QR code
        settings.setData("Hello 123456789");//Set the data 
        settings.setShowText(false);// Make the textual data invisible
        settings.setQRCodeDataMode(QRCodeDataMode.Alpha_Number);//Set data mode
        settings.setImageWidth(50);// Set widthfor the created QR code image
        settings.setImageHeight(50);// Set height for the created QR code image
        settings.setX(3.0f);//Set width for QR code model
        settings.setQRCodeECL(QRCodeECL.H);//Set QR code ECL
        settings.hasBorder(false);//make the border invisible

        BarCodeGenerator barCodeGenerator = new BarCodeGenerator(settings);//Instantiage BarCodeGenerator object

        BufferedImage bufferedImage = barCodeGenerator.generateImage();//Generate image data based on settings and save it to BufferedImage instance
        ImageIO.write(bufferedImage, "png", new File("QRCode.png"));//Save the QR code as PNG
    }
}

Output

Invisiblize Textual Data When Creating Barcode&QR code in Java

Thursday, 01 July 2021 06:31

Set Text Alignment within a Shape in Java

This article demonstrates how to set text horizontal and vertical alignment within a shape using Spire.Presentation for Java.

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

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

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

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

        //Add a shape 
        IAutoShape textShape = presentation.getSlides().get(0).getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle2D.Float(50, 50, 400, 200));
        textShape.getShapeStyle().getLineColor().setColor(Color.DARK_GRAY);
        textShape.getFill().setFillType(FillFormatType.NONE);

        //Remove the default paragraphs 
        textShape.getTextFrame().getParagraphs().clear();

        //Add a paragraph and append some text to it 
        textShape.getTextFrame().getParagraphs().append(new ParagraphEx());
        textShape.getTextFrame().getParagraphs().get(0).getTextRanges().append(new PortionEx("Text Alignment"));
        textShape.getTextFrame().getParagraphs().get(0).getTextRanges().get(0).setFontHeight(20f);
        textShape.getTextFrame().getParagraphs().get(0).getTextRanges().get(0).setLatinFont(new TextFont("Arial"));
        textShape.getTextFrame().getParagraphs().get(0).getTextRanges().get(0).getFill().setFillType(FillFormatType.SOLID);
        textShape.getTextFrame().getParagraphs().get(0).getTextRanges().get(0).getFill().getSolidColor().setColor(Color.BLACK);

        //Set text horizontal alignment to right 
        textShape.getTextFrame().getParagraphs().get(0).setAlignment(TextAlignmentType.RIGHT);

        //Set text vertical alignment to bottom 
        textShape.getTextFrame().setAnchoringType(TextAnchorType.BOTTOM);

        //Save to file
        presentation.saveToFile("output/TextAlignment.pptx",FileFormat.PPTX_2013);
    }
}

Set Text Alignment within a Shape in Java

This article demonstrates how to get the position of text in PowerPoint in Java using Spire.Presentation for Java.

import com.spire.presentation.IAutoShape;
import com.spire.presentation.ISlide;
import com.spire.presentation.Presentation;

import java.awt.geom.Point2D;

public class GetPositionOfText {
    public static void main(String []args) throws Exception {
        //Create a Presentation instance
        Presentation ppt = new Presentation();
        //Load a PowerPoint document
        ppt.loadFromFile("Sample.pptx");

        //Get the first slide
        ISlide slide = ppt.getSlides().get(0);
        //Get the first shape
        IAutoShape shape = (IAutoShape)slide.getShapes().get(0);
        //Get location of text in the shape
        Point2D location =shape.getTextFrame().getTextLocation();

        //Print out the x and y coordinates of the location relative to slide
        String  point1="Text's position relative to Slide: x= "+location.getX()+" y = "+location.getY();
        System.out.println(point1);

        //Print out the x and y coordinates of the location relative to shape
        String point2 = "Text's position relative to shape: x= " + (location.getX() - shape.getLeft()) + "  y = " + (location.getY() - shape.getTop());
        System.out.println(point2);
    }
}

Output:

Get Position of Text in PowerPoint in Java

In the earlier tutorial, we have given a brief introduction on how to insert Textbox in Word and this article will demonstrate how to position the text vertically in a text box using Spire.Doc for .NET.

C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System;

namespace WordTextbox
{
    class Program
    {
        static void Main(string[] args)
        {
            // Instantiate document object
            Document document = new Document();

            //Add a section 
            Section section = document.AddSection();

            //Set the margin
            section.PageSetup.Margins.Left = 90;
            section.PageSetup.Margins.Right = 90;
            Paragraph paragraph = section.AddParagraph();

            //Add texbox 1
            TextBox textBox1 = paragraph.AppendTextBox(section.PageSetup.Margins.Left - 20, section.PageSetup.PageSize.Height + 20);
           
            //Fix the position of textbox 
            textBox1.Format.HorizontalOrigin = HorizontalOrigin.Page;
            textBox1.Format.HorizontalPosition = 0;
            textBox1.Format.VerticalPosition = -10f;
            textBox1.Format.VerticalOrigin = VerticalOrigin.Page;

            //Set the text vertically
            textBox1.Format.TextAnchor = ShapeVerticalAlignment.Center;
            textBox1.Format.LayoutFlowAlt = TextDirection.LeftToRight;

            //Add text and set the font
            Paragraph textboxPara1 = textBox1.Body.AddParagraph();
            TextRange txtrg = textboxPara1.AppendText("Name_______Number_________Class__________");
            txtrg.CharacterFormat.FontName = "Arial";
            txtrg.CharacterFormat.FontSize = 10;
            txtrg.CharacterFormat.TextColor = System.Drawing.Color.Black;
            textboxPara1.Format.HorizontalAlignment = HorizontalAlignment.Center;

            //Save the document
            document.SaveToFile("Result.docx");

        }
    }
}
VB.NET
Namespace WordTextbox
    
    Class Program
        
        Private Shared Sub Main(ByVal args() As String)
            Dim document As Document = New Document
            Dim section As Section = document.AddSection
            section.PageSetup.Margins.Left = 90
            section.PageSetup.Margins.Right = 90
            Dim paragraph As Paragraph = section.AddParagraph
            Dim textBox1 As TextBox = paragraph.AppendTextBox((section.PageSetup.Margins.Left - 20), (section.PageSetup.PageSize.Height + 20))
            textBox1.Format.HorizontalOrigin = HorizontalOrigin.Page
            textBox1.Format.HorizontalPosition = 0
            textBox1.Format.VerticalPosition = -10!
            textBox1.Format.VerticalOrigin = VerticalOrigin.Page
            textBox1.Format.TextAnchor = ShapeVerticalAlignment.Center
            textBox1.Format.LayoutFlowAlt = TextDirection.LeftToRight
            Dim textboxPara1 As Paragraph = textBox1.Body.AddParagraph
            Dim txtrg As TextRange = textboxPara1.AppendText("Name_______Number_________Class__________")
            txtrg.CharacterFormat.FontName= "Arial"
            txtrg.CharacterFormat.FontSize = 10
            txtrg.CharacterFormat.TextColor = System.Drawing.Color.Black
            textboxPara1.Format.HorizontalAlignment = HorizontalAlignment.Center
            document.SaveToFile("Result.docx")
        End Sub
    End Class
End Namespace

Output

How to Set Text Direction in Textbox in C#, VB.NET

Page 9 of 143