Monday, 11 January 2021 07:13

Add Line Numbers to a PDF in C#, VB.NET

This article demonstrates how to add line numbers before chunks of text in a PDF page by using Spire.PDF for .NET.

Below is a screenshot of the input document.

Add Line Numbers to a PDF in C#, VB.NET

C#
using Spire.Pdf;
using Spire.Pdf.General.Find;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace AddLineNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument of instance
            PdfDocument doc = new PdfDocument();

            //Load a PDF document
            doc.LoadFromFile(@"G:\360MoveData\Users\Administrator\Desktop\sample.pdf");

            //Get the first page
            PdfPageBase page = doc.Pages[0];

            //Find the spcific text in the fisrt line
            PdfTextFind topLine = page.FindText("C# (pronounced See Sharp)", TextFindParameter.None).Finds[0];

            //Get the line height
            float lineHeight = topLine.Bounds.Height;

            //Get the Y coordinate of the selected text
            float y = topLine.Bounds.Y;

            //Find the spcific text in the second line
            PdfTextFind secondLine = page.FindText("language. C#", TextFindParameter.None).Finds[0];

            //Calculate the line spacing
            float lineSpacing = secondLine.Bounds.Top - topLine.Bounds.Bottom;

            //Find the specific text in the last line
            PdfTextFind bottomLine = page.FindText("allocation of objects", TextFindParameter.None).Finds[0];

            //Get the height of the chunks 
            float height = bottomLine.Bounds.Bottom;

            //Create a font
            PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 11f);

            int i = 1;
            while (y < height)
            {
                //Draw line number before a specific line of text
                page.Canvas.DrawString(i.ToString(), font, PdfBrushes.Black, new PointF(15, y));
                y += lineHeight + lineSpacing;
                i++;
            }

            //Save the document
            doc.SaveToFile("result.pdf");
        }
    }
}
VB.NET
Imports Spire.Pdf
Imports Spire.Pdf.General.Find
Imports Spire.Pdf.Graphics
Imports System.Drawing
 
Namespace AddLineNumber
    Class Program
        Shared  Sub Main(ByVal args() As String)
            'Create a PdfDocument of instance
            Dim doc As PdfDocument =  New PdfDocument() 
 
            'Load a PDF document
            doc.LoadFromFile("G:\360MoveData\Users\Administrator\Desktop\sample.pdf")
 
            'Get the first page
            Dim page As PdfPageBase =  doc.Pages(0) 
 
            'Find the spcific text in the fisrt line
            Dim topLine As PdfTextFind =  page.FindText("C# (pronounced See Sharp)",TextFindParameter.None).Finds(0) 
 
            'Get the line height
            Dim lineHeight As single =  topLine.Bounds.Height 
 
            'Get the Y coordinate of the selected text
            Dim y As single =  topLine.Bounds.Y 
 
            'Find the spcific text in the second line
            Dim secondLine As PdfTextFind =  page.FindText("language. C#",TextFindParameter.None).Finds(0) 
 
            'Calculate the line spacing
            Dim lineSpacing As single =  secondLine.Bounds.Top - topLine.Bounds.Bottom 
 
            'Find the specific text in the last line
            Dim bottomLine As PdfTextFind =  page.FindText("allocation of objects",TextFindParameter.None).Finds(0) 
 
            'Get the height of the chunks 
            Dim height As single =  bottomLine.Bounds.Bottom 
 
            'Create a font
            Dim font As PdfFont =  New PdfFont(PdfFontFamily.TimesRoman,11f) 
 
            Dim i As Integer =  1 
            While y < height
                'Draw line number before a specific line of text
                page.Canvas.DrawString(i.ToString(),font,PdfBrushes.Black,New PointF(15,y))
                y += lineHeight + lineSpacing
                i = i + 1
            End While
 
            'Save the document
            doc.SaveToFile("result.pdf")
        End Sub
    End Class
End Namespace

Output

Add Line Numbers to a PDF in C#, VB.NET

We have introduced how to compare two Word documents in C# and VB.NET. From Spire.Doc V8.12.14, it supports to get the differences between two Word documents in a structure list. This article will show you how to use Spire.Doc to get the differences by comparing two Word documents.

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

namespace GetWordDifferences
    {
    class Program
    {
        static void Main(string[] args)

        {
            //Load the first Word document
            Document doc1 = new Document();
            doc1.LoadFromFile("Sample1.docx");

            //Load the second Word document
            Document doc2 = new Document();
            doc2.LoadFromFile("Sample2.docx");

            //Compare the two Word documents
            doc1.Compare(doc2, "Author");

            foreach (Section sec in doc1.Sections)
            {
                foreach (DocumentObject docItem in sec.Body.ChildObjects)
                {
                    if (docItem is Paragraph)
{
                        Paragraph para = docItem as Paragraph;
                        if (para.IsInsertRevision)
                        { 
                            EditRevision insRevison = para.InsertRevision;
                            EditRevisionType insType = insRevison.Type; 
                            string insAuthor = insRevison.Author; 
                            DateTime insDateTime = insRevison.DateTime; 
                        }

                        else if (para.IsDeleteRevision)
                        { 
                            EditRevision delRevison = para.DeleteRevision; 
                            EditRevisionType delType = delRevison.Type; 
                            string delAuthor = delRevison.Author; 
                            DateTime delDateTime = delRevison.DateTime; 
                        }

                        foreach (ParagraphBase paraItem in para.ChildObjects)
                        {
                            if (paraItem.IsInsertRevision)
                            { 
                                EditRevision insRevison = paraItem.InsertRevision; 
                                EditRevisionType insType = insRevison.Type; 
                                string insAuthor = insRevison.Author; 
                                DateTime insDateTime = insRevison.DateTime; 
                            }

                            else if (paraItem.IsDeleteRevision)
                            { 
                                EditRevision delRevison = paraItem.DeleteRevision; 
                                EditRevisionType delType = delRevison.Type; 
                                string delAuthor = delRevison.Author; 
                                DateTime delDateTime = delRevison.DateTime; 
                            }

                        }
                    }
                }
            }

            //Get the difference about revisions
            DifferRevisions differRevisions = new DifferRevisions(doc1);
            var insetRevisionsList = differRevisions.InsertRevisions;
            var deletRevisionsList = differRevisions.DeleteRevisions;      
        }
    }
 }
VB.NET
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Imports Spire.Doc.Formatting.Revisions
Imports System

Namespace GetWordDifferences
    
    Class Program
        
        Private Shared Sub Main(ByVal args() As String)
            'Load the first Word document
            Dim doc1 As Document = New Document
            doc1.LoadFromFile("Sample1.docx")
            'Load the second Word document
            Dim doc2 As Document = New Document
            doc2.LoadFromFile("Sample2.docx")
            'Compare the two Word documents
            doc1.Compare(doc2, "Author")
            For Each sec As Section In doc1.Sections
                For Each docItem As DocumentObject In sec.Body.ChildObjects
                    If (TypeOf docItem Is Paragraph) Then
                        Dim para As Paragraph = CType(docItem,Paragraph)
                        If para.IsInsertRevision Then
                            Dim insRevison As EditRevision = para.InsertRevision
                            Dim insType As EditRevisionType = insRevison.Type
                            Dim insAuthor As String = insRevison.Author
                            Dim insDateTime As DateTime = insRevison.DateTime
                        ElseIf para.IsDeleteRevision Then
                            Dim delRevison As EditRevision = para.DeleteRevision
                            Dim delType As EditRevisionType = delRevison.Type
                            Dim delAuthor As String = delRevison.Author
                            Dim delDateTime As DateTime = delRevison.DateTime
                        End If
                        
                        For Each paraItem As ParagraphBase In para.ChildObjects
                            If paraItem.IsInsertRevision Then
                                Dim insRevison As EditRevision = paraItem.InsertRevision
                                Dim insType As EditRevisionType = insRevison.Type
                                Dim insAuthor As String = insRevison.Author
                                Dim insDateTime As DateTime = insRevison.DateTime
                            ElseIf paraItem.IsDeleteRevision Then
                                Dim delRevison As EditRevision = paraItem.DeleteRevision
                                Dim delType As EditRevisionType = delRevison.Type
                                Dim delAuthor As String = delRevison.Author
                                Dim delDateTime As DateTime = delRevison.DateTime
                            End If
                            
                        Next
                    End If
                    
                Next
            Next
            'Get the difference about revisions
            Dim differRevisions As DifferRevisions = New DifferRevisions(doc1)
            Dim insetRevisionsList = differRevisions.InsertRevisions
            Dim deletRevisionsList = differRevisions.DeleteRevisions
        End Sub
    End Class
End Namespace
Tuesday, 29 December 2020 07:12

Hide or display layers in PDF in Java

This article will demonstrate how to hide and display Layers in a PDF document using Spire.PDF for Java.

Hide all layers:

import com.spire.pdf.*;
import com.spire.pdf.graphics.layer.*;

public class invisibleAllPdfLayers {
    public static void main(String[] args) {
        //Load the sample document
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("layerSample.pdf");

        for (int i = 0; i < doc.getLayers().getCount(); i++)
        {
            //Show all the Pdf layers
            //doc.getLayers().get(i).setVisibility(PdfVisibility.On);
            //Set all the Pdf layers invisible
            doc.getLayers().get(i).setVisibility(PdfVisibility.Off);
        }

        //Save to document to file
        doc.saveToFile("output/invisibleAllPdfLayers.pdf", FileFormat.PDF);
    }
}

Hide or display layers in PDF in Java

Hide some of the PDF layers:

import com.spire.pdf.*;
import com.spire.pdf.graphics.layer.*;

public class invisibleParticularPdfLayers {
    public static void main(String[] args) {
        //Load the sample document
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("layerSample.pdf");

        //Hide the first layer by index
        doc.getLayers().get(0).setVisibility(PdfVisibility.Off);

        //Hide the layer by name with blue line1
        for (int i = 0; i < doc.getLayers().getCount(); i++)
        {
            if("blue line1".equals(doc.getLayers().get(i).getName())){
                doc.getLayers().get(i).setVisibility(PdfVisibility.Off);
            }
        }

        //Save to document to file
        doc.saveToFile("output/invisiblePaticularPdfLayers.pdf", FileFormat.PDF);
    }
}

Hide or display layers in PDF in Java

Tuesday, 22 December 2020 07:33

Java expand and collapse the bookmarks for PDF

This article will demonstrate how to expand or collapse the bookmarks when viewing the PDF files.

Expand all bookmarks on PDF

import com.spire.pdf.PdfDocument;

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

        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("Sample.pdf");

        //Set true to expand all bookmarks; set false to collapse all bookmarks
        doc.getViewerPreferences().setBookMarkExpandOrCollapse(true);

        doc.saveToFile("output/expandAllBookmarks_out.pdf");
        doc.close();
    }
}

Output:

Java expand and collapse the bookmarks for PDF

Expand specific bookmarks on PDF

import com.spire.pdf.PdfDocument;
import com.spire.pdf.bookmarks.*;

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

        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("Sample.pdf");

        //Set BookMarkExpandOrCollapse as "true" for the first bookmarks
        doc.getBookmarks().get(0).setExpandBookmark(true);

        //Set BookMarkExpandOrCollapse as "false" for the first level of the second bookmarks
        PdfBookmarkCollection pdfBookmark = doc.getBookmarks().get(1);
        pdfBookmark.get(0).setExpandBookmark(false);

        doc.saveToFile("output/expandSpecificBookmarks_out.pdf");
        doc.close();
    }
}

Only expand the first bookmarks

Java expand and collapse the bookmarks for PDF

This article demonstrates how to split a workbook into multiple Excel files (each containing one worksheet) by using Spire.XLS for Java.

import com.spire.xls.FileFormat;
import com.spire.xls.Workbook;

public class SplitWorkbook {

    public static void main(String[] args) {

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

        //Load an Excel document
        wb.loadFromFile("C:\\Users\\Administrator\\Desktop\\data.xlsx");

        //Declare a Workbook variable
        Workbook newWb;

        //Declare a String variable
        String sheetName;

        //Specify the folder path, which is used to store the generated Excel files
        String folderPath = "C:\\Users\\Administrator\\Desktop\\Output\\";

        //Loop through the worksheets in the source file
        for (int i = 0; i < wb.getWorksheets().getCount(); i++) {

            //Initialize the Workbook object
            newWb = new Workbook();

            //Remove the default sheets
            newWb.getWorksheets().clear();

            //Add the the specific worksheet of the source document to the new workbook
            newWb.getWorksheets().addCopy(wb.getWorksheets().get(i));

            //Get the worksheet name
            sheetName = wb.getWorksheets().get(i).getName();

            //Save the new workbook to the specified folder 
            newWb.saveToFile(folderPath + sheetName + ".xlsx", FileFormat.Version2013);
        }
    }
}

Split a Workbook into Separate Excel Files in Java

This article will demonstrate how to set the zoom factor/percentage (such as default, 100 percent or any other zoom factors as required) and the viewer preference by using Spire.PDF for Java in Java applications.

Set the zoom factor

import com.spire.pdf.*;
import com.spire.pdf.actions.*;
import com.spire.pdf.general.*;

import java.awt.geom.*;

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

        //Load the sample document
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("Sample.pdf");

        //Get the first page of PDF
        PdfPageBase page = doc.getPages().get(0);

        //Set pdf destination
        PdfDestination dest = new PdfDestination(page);
        dest.setMode(PdfDestinationMode.Location);
        dest.setLocation(new Point2D.Float(-40f, -40f));

        //Set zoom factor
        dest.setZoom(0.8f);

        //Set action
        PdfGoToAction gotoAction = new PdfGoToAction(dest);
        doc.setAfterOpenAction(gotoAction);

        //Save pdf document
        String output = "output/setZoomFactor.pdf";
        doc.saveToFile(output);
    }
}

Output:

Java set the viewer preference and zoom factor for PDF

Set the viewer preference

import com.spire.pdf.*;

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

        //Load the sample document
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("Sample.pdf");

        //Set viewer reference
        doc.getViewerPreferences().setCenterWindow(true);
        doc.getViewerPreferences().setDisplayTitle(false);
        doc.getViewerPreferences().setFitWindow(false);
        doc.getViewerPreferences().setHideMenubar(true);
        doc.getViewerPreferences().setHideToolbar(true);
        doc.getViewerPreferences().setPageLayout(PdfPageLayout.Two_Column_Left);

        //Save pdf document
        String output = "output/viewerPreference.pdf";
        doc.saveToFile(output);
    }
}

Output:

Java set the viewer preference and zoom factor for PDF

When you receive a large Excel document that has multiple worksheets, you may want to save each worksheet out as a separate Excel file. This article will introduce how to split a workbook by using Spire.XLS with C# or VB.NET.

C#
using Spire.Xls;
using System;

namespace SplitWorkbook
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook object
            Workbook wb = new Workbook();

            //Load an Excel document
            wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\data.xlsx");

            //Declare a new Workbook variable
            Workbook newWb;

            //Declare a String variable
            String sheetName;

            //Specify the folder path, which is used to store the generated Excel files
            String folderPath = "C:\\Users\\Administrator\\Desktop\\Output\\";

            //Loop through the worksheets in the source file
            for (int i = 0; i < wb.Worksheets.Count; i++)
            {

                //Initialize the Workbook object
                newWb = new Workbook();

                //Remove the default sheets
                newWb.Worksheets.Clear();

                //Add the the specific worksheet of the source document to the new workbook
                newWb.Worksheets.AddCopy(wb.Worksheets[i]);

                //Get the worksheet name
                sheetName = wb.Worksheets[i].Name;

                //Save the new workbook to the specified folder
                newWb.SaveToFile(folderPath + sheetName + ".xlsx", ExcelVersion.Version2013);
            }
        }
    }
}
VB.NET
Imports Spire.Xls
Imports System
 
Namespace SplitWorkbook
    Class Program
        Shared  Sub Main(ByVal args() As String)
            'Create a Workbook object
            Dim wb As Workbook =  New Workbook() 
 
            'Load an Excel document
            wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\data.xlsx")
 
            'Declare a new Workbook variable
            Dim NewWb As Workbook
 
            'Declare a String variable
            Dim sheetName As String
 
            'Specify the folder path, which is used to store the generated Excel files
            Dim folderPath As String =  "C:\\Users\\Administrator\\Desktop\\Output\\" 
 
            'Loop through the worksheets in the source file
            Dim i As Integer
            For  i = 0 To  wb.Worksheets.Count- 1  Step  i + 1
 
                'Initialize the Workbook object
                NewWb = New Workbook()
 
                'Remove the default sheets
                NewWb.Worksheets.Clear()
 
                'Add the the specific worksheet of the source document to the new workbook
                NewWb.Worksheets.AddCopy(wb.Worksheets(i))
 
                'Get the worksheet name
                sheetName = wb.Worksheets(i).Name
 
                'Save the new workbook to the specified folder
                NewWb.SaveToFile(folderPath + sheetName + ".xlsx", ExcelVersion.Version2013)
            Next
        End Sub
    End Class
End Namespace

Output

Split a Workbook into Multiple Excel Documents in C#, VB.NET

Wednesday, 09 December 2020 08:11

Java draw Superscript and Subscript Text in PDF

This article will show you how to use Spire.PDF for Java to draw superscript and subscript text to PDF file in Java applications.

Draw Superscript Text

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.*;

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

        //Create a new PdfDocument instance
        PdfDocument doc = new PdfDocument();
        //Add a page to pdf
        PdfPageBase page = doc.getPages().add();

        //Set the font
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.PLAIN,14),true);
        PdfSolidBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.black));

        //Set initial (x, y) coordinate
        float x = 120f;
        float y = 100f;

        //Draw text string
        String text = "Sample Text";
        page.getCanvas().drawString(text, font, brush, new Point2D.Float(x, y));

        //Measure the string
        Dimension2D size = font.measureString(text);
        x += size.getWidth();

        //Draw the text string and set the format as Superscript
        PdfStringFormat format = new PdfStringFormat();
        format.setSubSuperScript(PdfSubSuperScript.Super_Script);
        text = "Superscrip";
        page.getCanvas().drawString(text, font, brush, new Point2D.Float(x, y), format);

        //Save the document to file
        String result="output/superScript.pdf";
        doc.saveToFile(result);
    }
}

Effective screenshot:

Java draw Superscript and Subscript Text in PDF

Draw Subscript Text

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.*;

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

        //Create a new PdfDocument instance
        PdfDocument doc = new PdfDocument();
        //Add a page to pdf
        PdfPageBase page = doc.getPages().add();

        //Set the font
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.PLAIN,14),true);
        PdfSolidBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.black));

        //Set initial (x, y) coordinate
        float x = 120f;
        float y = 100f;

        //Draw text string
        String text = "Sample Text";
        page.getCanvas().drawString(text, font, brush, new Point2D.Float(x, y));

        //Measure the string
        Dimension2D size = font.measureString(text);
        x += size.getWidth();

        //Draw the text string and set the format as Subscript
        PdfStringFormat format = new PdfStringFormat();
        format.setSubSuperScript(PdfSubSuperScript.Sub_Script);
        text = "Subscrip";
        page.getCanvas().drawString(text, font, brush, new Point2D.Float(x, y), format);

        //Save the document to file
        String result="output/subScript.pdf";
        doc.saveToFile(result);
    }
}

Output:

Java draw Superscript and Subscript Text in PDF

This article demonstrates how to split a worksheet into several Excel documents by using Spire.XLS for Java.

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

public class SplitWorksheet {

    public static void main(String[] args) {

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

        //Get the first worksheet
        Worksheet sheet = bookOriginal.getWorksheets().get(0);

        //Get the header row
        CellRange headerRow = sheet.getCellRange(1, 1, 1, 5);

        //Get two cell ranges
        CellRange range1 = sheet.getCellRange(2, 1, 6, 5);
        CellRange range2 = sheet.getCellRange(7, 1, 11, 5);

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

        //Copy the header row and range 1 to the new workbook
        sheet.copy(headerRow, newBook1.getWorksheets().get(0), 1, 1, true, false);
        sheet.copy(range1, newBook1.getWorksheets().get(0), 2, 1, true, false);

        //Copy the column width from the original workbook to the new workbook
        for (int i = 0; i < sheet.getLastColumn(); i++) {

            newBook1.getWorksheets().get(0).setColumnWidth(i + 1, sheet.getColumnWidth(i + 1));
        }

        //Save the new workbook to an Excel file
        newBook1.saveToFile("Sales.xlsx", ExcelVersion.Version2016);

        //Copy the header row and range 2 to another workbook, and save it to another Excel file
        Workbook newBook2 = new Workbook();
        sheet.copy(headerRow, newBook2.getWorksheets().get(0), 1, 1, true, false);
        sheet.copy(range2, newBook2.getWorksheets().get(0), 2, 1, true, false);
        for (int i = 0; i < sheet.getLastColumn(); i++) {

            newBook2.getWorksheets().get(0).setColumnWidth(i + 1, sheet.getColumnWidth(i + 1));
        }
        newBook2.saveToFile("Technicians.xlsx", ExcelVersion.Version2016);
    }
}

Split a Worksheet into Several Excel Files in Java

The following code snippets demonstrate how to use Spire.Doc for Java to set the page size and page orientation for word document in Java applications.

import com.spire.doc.*;
import com.spire.doc.documents.*;

public class WordPageSetup {
    public static void main(String[] args) throws Exception {
        //Load the sample document
        Document doc= new Document();
        doc.loadFromFile("Sample.docx");
        //Get the first section
        Section section = doc.getSections().get(0);
        //Set the page size
        section.getPageSetup().setPageSize(PageSize.A3);
        //Set the page orientation
        section.getPageSetup().setOrientation(PageOrientation.Landscape);
        //Save the document to file
        doc.saveToFile("Result.docx",FileFormat.Docx_2013);
    }
}

Effective screenshot:

Java set the page size and page orientation for Word

Page 1 of 130