Extract Images from PDF in Java – Preserve Quality & Filter Noise

When dealing with PDF documents that contain images—such as scanned reports, digital brochures, or design portfolios—you may need to extract these images for reuse or analysis. In this article, we'll show you how to extract images from PDF in Java, covering both basic usage and advanced image extracting techniques using the Spire.PDF for Java library.
Whether you're creating a PDF image extractor in Java or simply looking to extract images from a PDF file using Java code, this guide will walk you through the process step by step.
Guide Outline
- Getting Started – Tools and Setup
- Extract All Images from a PDF in Java
- Advanced Tips for More Precise Image Extraction
- Frequently Asked Questions
- Conclusion
Getting Started – Tools and Setup
Extracting images from PDF files in Java can be challenging without third-party libraries. While PDFs may contain valuable image assets—such as scanned pages, charts, or embedded graphics—these elements are often encoded or compressed in ways that native Java APIs can’t handle directly.
Spire.PDF for Java provides a high-level, reliable way to locate and extract embedded or inline images from PDF files. Whether you’re building an automation tool or a document parser, this library helps you extract image content efficiently and with full quality.
Before getting started, make sure you have the following development tools ready:
- Java Development Kit (JDK) 1.6 or above
- Spire.PDF for Java (Free or commercial version)
- An IDE (e.g., IntelliJ IDEA, Eclipse)
Maven Dependency:
<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.pdf</artifactId>
<version>12.3.9</version>
</dependency>
</dependencies>
You can use Free Spire.PDF for Java for smaller tasks.
Extract All Images from a PDF in Java
The most straightforward way to extract images from a PDF is by using the PdfImageHelper class in Spire.PDF for Java. This utility scans each page, locates embedded or inline images, and returns both the image data and metadata such as size and position.
Code Example: Basic Image Extraction
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.utilities.PdfImageHelper;
import com.spire.pdf.utilities.PdfImageInfo;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ExtractAllImagePDF {
public static void main(String[] args) throws IOException {
// Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
pdf.loadFromFile("input.pdf");
// Create an image helper instance
PdfImageHelper imageHelper = new PdfImageHelper();
// Loop through each page to extract images
for (int i = 0; i < pdf.getPages().getCount(); i++) {
PdfPageBase page = pdf.getPages().get(i);
PdfImageInfo[] imagesInfo = imageHelper.getImagesInfo(page);
for (int j = 0; j < imagesInfo.length; j++) {
BufferedImage image = imagesInfo[j].getImage();
File file = new File("output/Page" + i + "_Image" + j + ".png");
ImageIO.write(image, "png", file);
}
}
pdf.close();
}
}
Make sure the output folder exists before running the code to avoid IOException.
How It Works
-
PdfDocument loads and holds the structure of the input PDF.
-
PdfPageBase represents a single page inside the PDF.
-
PdfImageHelper.getImagesInfo(PdfPageBase) scans a specific page and returns an array of PdfImageInfo, each containing a detected image.
-
Each PdfImageInfo includes:
- The image itself as a BufferedImage
- Metadata like size, DPI, and page index
-
ImageIO.write() supports common formats like "png", "jpg", and "bmp" — you can change the format string as needed.
After running the extraction code, you’ll get a folder containing the exported images from the PDF, each saved in a separate file.

These high-level abstractions save you from manually decoding image XObjects or parsing raw streams—making PDF image extraction in Java easier and cleaner.
To save full PDF pages as images instead of just extracting embedded images, follow our guide on saving PDF pages as images in Java.
Advanced Tips for More Precise Image Extraction
Extracting images from a PDF is not always a one-size-fits-all operation. Some files contain layout elements like background layers, small decorative icons, or embedded metadata images. The following advanced tips help you refine your extraction logic for better results:
Skip Background Images (Optional)
Some PDF files include background images, such as watermarks or decorative layers. When these are defined using standard PDF background settings, they are typically extracted as the first image on the page. To focus on meaningful content, simply skip the first extracted image per page.
for (int i = 1; i < imagesInfo.length; i++) { // Skip background image
BufferedImage image = imagesInfo[i].getImage();
ImageIO.write(image, "PNG", new File("output/image_" + (i - 1) + ".png"));
}
You can also check the getBounds() property to assess image dimensions and placement before deciding to skip.
Filter by Image Size (Ignore Small Icons)
To exclude small elements like buttons or logos, add a size threshold before saving:
BufferedImage image = imagesInfo[i].getImage();
if (image.getWidth() > 200 && image.getHeight() > 200) {
ImageIO.write(image, "PNG", new File("output/image_" + i + ".png"));
}
This helps keep the output folder clean and focused on relevant image content.
Export Images in Various Formats or Streams
You can output images in various formats or streams depending on your use case:
ImageIO.write(image, "JPEG", new File("output/image_" + i + ".jpg")); // compressed
ImageIO.write(image, "BMP", new File("output/image_" + i + ".bmp")); // high-quality
- Use PNG or BMP for lossless quality (e.g., archival or OCR).
- Use JPEG for web or lower storage usage.
You can also write images to a ByteArrayOutputStream or other output streams for further processing:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ImageIO.write(image, "PNG", stream);
Also Want to Extract Images from PDF Attachments?
If your PDF contains embedded file attachments like .jpg or .png images, you'll need a different approach. See our guide here:
How to Extract Attachments from PDF in Java
FAQ for Image Extraction from PDF in Java
Can I extract images from a PDF file using Java?
Yes. Using Spire.PDF for Java, you can easily extract embedded or inline images from any PDF page with a few lines of code.
Will extracted images retain their original quality?
Absolutely. Images are extracted in their original resolution and encoding. You can save them in PNG or BMP format to preserve full quality.
What’s the difference between image extraction and rendering PDF as an image?
Rendering a PDF page creates a bitmap version of the entire page (including text and layout), while image extraction pulls out only the embedded image objects that were originally inserted in the file.
Does this work for scanned PDFs?
Yes. Many scanned PDFs contain full-page raster images (e.g., JPGs or TIFFs). These are extracted just like any other embedded image.
Conclusion
Extracting images from PDF files using Java is fast and efficient with Spire.PDF. Whether you're analyzing marketing materials, scanned reports, or design portfolios, this Java PDF image extractor solution helps you programmatically access and save high-quality images embedded in your documents.
For more advanced cases—such as excluding layout images or processing attachments—the API offers enough flexibility to customize your approach.
To fully unlock the capabilities of Spire.PDF for Java without any evaluation limitations, you can apply for a free temporary license.
Apply a Slide Master to a Presentation in C#, VB.NET
Every PowerPoint presentation has a slide master which contains all the styles for your slides. You can quickly change the look of your entire presentation by selecting the slide master, and then adopting a theme, adding a background picture or changing the color scheme.
In this article, you will learn how to access and customize the slide master in an existing presentation.
Source File:

Detail steps:
Step 1: Load the source file.
Presentation ppt = new Presentation(); ppt.LoadFromFile(@"sample.pptx");
Step 2: Get the first slide master from the presentation.
IMasterSlide masterSlide = ppt.Masters[0];
Step 3: Customize the background of the slide master.
string backgroundPic = "background.png"; RectangleF rect = new RectangleF(0, 0, ppt.SlideSize.Size.Width, ppt.SlideSize.Size.Height); masterSlide.SlideBackground.Fill.FillType = FillFormatType.Picture; IEmbedImage image = masterSlide.Shapes.AppendEmbedImage(ShapeType.Rectangle, backgroundPic, rect); masterSlide.SlideBackground.Fill.PictureFill.Picture.EmbedImage = image as IImageData;
Step 4: Change the color scheme.
masterSlide.Theme.ColorScheme.Accent1.Color = Color.Red; masterSlide.Theme.ColorScheme.Accent2.Color = Color.RosyBrown; masterSlide.Theme.ColorScheme.Accent3.Color = Color.Ivory; masterSlide.Theme.ColorScheme.Accent4.Color = Color.Lavender; masterSlide.Theme.ColorScheme.Accent5.Color = Color.Black;
Step 5: Add an image to the slide master. If you want, you can add any other document elements to slide master so that they can display on each slide.
string logo = "logo.png"; IEmbedImage imageShape = masterSlide.Shapes.AppendEmbedImage(ShapeType.Rectangle, logo, new RectangleF(40, 40, 240, 65)); imageShape.Line.FillFormat.FillType = FillFormatType.None;
Step 6: Save the document.
ppt.SaveToFile("result.pptx", FileFormat.Pptx2013);
Result:

Full code:
using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.Drawing;
namespace ApplySlideMaster
{
class Program
{
static void Main(string[] args)
{
Presentation ppt = new Presentation();
ppt.LoadFromFile(@"sample.pptx");
IMasterSlide masterSlide = ppt.Masters[0];
string backgroundPic = "background.png";
string logo = "logo.png";
RectangleF rect = new RectangleF(0, 0, ppt.SlideSize.Size.Width, ppt.SlideSize.Size.Height);
masterSlide.SlideBackground.Fill.FillType = FillFormatType.Picture;
IEmbedImage image = masterSlide.Shapes.AppendEmbedImage(ShapeType.Rectangle, backgroundPic, rect);
masterSlide.SlideBackground.Fill.PictureFill.Picture.EmbedImage = image as IImageData;
masterSlide.Theme.ColorScheme.Accent1.Color = Color.Red;
masterSlide.Theme.ColorScheme.Accent2.Color = Color.RosyBrown;
masterSlide.Theme.ColorScheme.Accent3.Color = Color.Ivory;
masterSlide.Theme.ColorScheme.Accent4.Color = Color.Lavender;
masterSlide.Theme.ColorScheme.Accent5.Color = Color.Black;
IEmbedImage imageShape = masterSlide.Shapes.AppendEmbedImage
(ShapeType.Rectangle, logo, new RectangleF(40, 40, 240, 65));
imageShape.Line.FillFormat.FillType = FillFormatType.None;
ppt.SaveToFile("result.pptx", FileFormat.Pptx2013);
}
}
}
Imports Spire.Presentation
Imports Spire.Presentation.Drawing
Imports System.Drawing
Namespace ApplySlideMaster
Class Program
Private Shared Sub Main(args As String())
Dim ppt As New Presentation()
ppt.LoadFromFile("sample.pptx")
Dim masterSlide As IMasterSlide = ppt.Masters(0)
Dim backgroundPic As String = "background.png"
Dim logo As String = "logo.png"
Dim rect As New RectangleF(0, 0, ppt.SlideSize.Size.Width, ppt.SlideSize.Size.Height)
masterSlide.SlideBackground.Fill.FillType = FillFormatType.Picture
Dim image As IEmbedImage = masterSlide.Shapes.AppendEmbedImage(ShapeType.Rectangle, backgroundPic, rect)
masterSlide.SlideBackground.Fill.PictureFill.Picture.EmbedImage = TryCast(image, IImageData)
masterSlide.Theme.ColorScheme.Accent1.Color = Color.Red
masterSlide.Theme.ColorScheme.Accent2.Color = Color.RosyBrown
masterSlide.Theme.ColorScheme.Accent3.Color = Color.Ivory
masterSlide.Theme.ColorScheme.Accent4.Color = Color.Lavender
masterSlide.Theme.ColorScheme.Accent5.Color = Color.Black
Dim imageShape As IEmbedImage = masterSlide.Shapes.AppendEmbedImage(ShapeType.Rectangle, logo, New RectangleF(40, 40, 240, 65))
imageShape.Line.FillFormat.FillType = FillFormatType.None
ppt.SaveToFile("result.pptx", FileFormat.Pptx2013)
End Sub
End Class
End Namespace
Vertically align the text in table cell on Presentation slides
Spire.Presentation supports to align text vertically in a table cell on the presentation slides. In this article, we will show you how to use C# to align the text in table cell and set the text direction. Firstly, view the screenshot on Microsoft PowerPoint of the vertical alignment and the text direction:

Detail steps:
Step 1: Create a new PowerPoint document and load the sample document from file.
Presentation ppt = new Presentation();
ppt.LoadFromFile("Sample1.pptx",FileFormat.Pptx2010);
Step 2: Get the table shape from the first presentation slide.
ITable table = null;
foreach (IShape shape in ppt.Slides[0].Shapes)
{
if (shape is ITable)
{
table = (ITable)shape;
Step 3: Aligning the text vertically and set the text direction.
table[i, 0].TextAnchorType = TextAnchorType.Center; table[i, 0].VerticalTextType = VerticalTextType.Vertical270; table[i, 1].TextAnchorType = TextAnchorType.Center; table[i, 1].VerticalTextType = VerticalTextType.Horizontal; table[i, 2].TextAnchorType = TextAnchorType.Center; table[i, 2].VerticalTextType = VerticalTextType.Vertical;
Step 4: Save the document to file.
ppt.SaveToFile("Result.pptx", FileFormat.Pptx2010);
Effective screenshot after set the vertical alignment and the text direction:

Full codes of vertical align the text and set the text direction.:
using Spire.Presentation;
namespace AlignText
{
class Program
{
static void Main(string[] args)
{
Presentation ppt = new Presentation();
ppt.LoadFromFile("Sample1.pptx", FileFormat.Pptx2010);
ITable table = null;
foreach (IShape shape in ppt.Slides[0].Shapes)
{
if (shape is ITable)
{
table = (ITable)shape;
for (int i = 0; i < table.ColumnsList.Count; i++)
{
table[i, 0].TextAnchorType = TextAnchorType.Center;
table[i, 0].VerticalTextType = VerticalTextType.Vertical270;
table[i, 1].TextAnchorType = TextAnchorType.Center;
table[i, 1].VerticalTextType = VerticalTextType.Horizontal;
table[i, 2].TextAnchorType = TextAnchorType.Center;
table[i, 2].VerticalTextType = VerticalTextType.Vertical;
}
}
}
ppt.SaveToFile("Result.pptx", FileFormat.Pptx2010);
}
}
}
Set and Get Alternative Text (Title and Description) of PowerPoint Shapes in C#
With Spire.Presentation, we can programmatically set the Alternative Text for PowerPoint shapes along with get the Alternative Text of PowerPoint shapes. This article demonstrates how we can use Spire.Presentation to accomplish this function.
Detail steps:
Step 1: Instantiate a Presentation object and load the PowerPoint file.
Presentation ppt = new Presentation();
ppt.LoadFromFile("Input.pptx");
Step 2: Get the first slide.
ISlide slide = ppt.Slides[0];
Step 3: Set or get the alternative text of the first Shape in the slide.
//Set the alternative text (title and description) slide.Shapes[0].AlternativeTitle = "Rectangle"; slide.Shapes[0].AlternativeText = "This is a Rectangle"; //Get the alternative text (title and description) //string title = slide.Shapes[0].AlternativeTitle; //string description = slide.Shapes[0].AlternativeText;
Step 4: Save the file.
ppt.SaveToFile("Output.pptx", FileFormat.Pptx2013);
Screenshot after setting alternative text:

Full code:
using Spire.Presentation;
namespace Set_and_Get_Alternative_Text_of_Shape
{
class Program
{
static void Main(string[] args)
{
//Instantiate a Presentation object
Presentation ppt = new Presentation();
//Load the PowerPoint file
ppt.LoadFromFile("Input.pptx");
//Get the first slide
ISlide slide = ppt.Slides[0];
//Set the alternative text (title and description)
slide.Shapes[0].AlternativeTitle = "Rectangle";
slide.Shapes[0].AlternativeText = "This is a Rectangle";
//Get the alternative text (title and description)
//string title = slide.Shapes[0].AlternativeTitle;
//string description = slide.Shapes[0].AlternativeText;
//Save the file
ppt.SaveToFile("Output.pptx", FileFormat.Pptx2013);
}
}
}
Add text watermark and image watermark to word document in C#
Text watermark and image watermark are two kinds of watermarks in Word document. The text watermark always shows some additional but related information to the word context. While image watermark is used to make the Word document be more attractive. This section will demonstrate how to use Spire.Doc to add text watermark and image watermark to Word document in C#.
Add Image Watermark in C#:
using Spire.Doc;
namespace SetImageWatermark
{
class Program
{
static void Main(string[] args)
{
{
//create a new instance of Document and load the document from file.
Document doc = new Document();
doc.LoadFromFile("Sample.docx", FileFormat.Docx2013);
//create a new instance of the PictureWatermark and load the picture from file.
PictureWatermark picture = new PictureWatermark();
picture.Picture = System.Drawing.Image.FromFile("logo.png");
//set the image watermark scaling and Washout property
picture.Scaling = 20;
picture.IsWashout = false;
//add the picture watermark
doc.Watermark = picture;
//save the document to file
doc.SaveToFile("ImageWatermark.docx", FileFormat.Docx2013);
}
}
}
}

Add Text Watermark in C#::
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
namespace SetTextWatermark
{
class Program
{
static void Main(string[] args)
{
{
//create a new instance of Document and load the document from file.
Document doc = new Document();
doc.LoadFromFile("Sample.docx", FileFormat.Docx2013);
//create a new instance of the TextWatermark
TextWatermark txtWatermark = new TextWatermark();
//set the text watermark with text string, font, color and layout.
txtWatermark.Text = "Confidential";
txtWatermark.FontSize = 45;
txtWatermark.Color = Color.Green;
txtWatermark.Layout = WatermarkLayout.Diagonal;
//add the text watermark
doc.Watermark = txtWatermark;
//save the file.
doc.SaveToFile("TextWatermark.docx", FileFormat.Docx2013);
}
}
}
}

Conditionally Format Dates in Excel with C#
Microsoft Excel provides 10 date options, ranging from yesterday to next month (see below image) to format selected cells based on the current date. Spire.XLS supports all of these options, in this article, we’re going to show you how to conditionally format dates in Excel using Spire.XLS. If you want to highlight cells based on a date in another cell, or create rules for other dates (i.e., more than a month from the current date), you will have to create your own conditional formatting rule based on a formula.

Detail steps:
Step 1: Initialize an object of Workbook class and load the Excel file.
Workbook workbook = new Workbook();
workbook.LoadFromFile("Input.xlsx");
Step 2: Get the first worksheet.
Worksheet sheet = workbook.Worksheets[0];
Step 3: Add a condition to the used range in the worksheet.
XlsConditionalFormats xcfs1 = sheet.ConditionalFormats.Add(); xcfs1.AddRange(sheet.AllocatedRange);
Step 4: Specify the format type of the condition as time period and set the time period as last 7 days.
IConditionalFormat format1 = xcfs1.AddTimePeriodCondition(TimePeriodType.Last7Days);
Step 5:Set the highlight color.
conditionalFormat.BackColor = Color.Orange;
Step 6:Save the file.
workbook.SaveToFile("ConditionallyFormatDates.xlsx", ExcelVersion.Version2013);
Screenshot::

Full Code:
using Spire.Xls;
using Spire.Xls.Core;
using Spire.Xls.Core.Spreadsheet.Collections;
using Spire.Xls.Core.Spreadsheet.ConditionalFormatting;
using System.Drawing;
namespace ConditionallyFormatDates
{
class Program
{
static void Main(string[] args)
{
//Initialize an object of Workbook class
Workbook workbook = new Workbook();
//Load the Excel file
workbook.LoadFromFile("Input.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
//Highlight cells that contain a date occurring in the last 7 days
XlsConditionalFormats xcfs1 = sheet.ConditionalFormats.Add();
xcfs1.AddRange(sheet.AllocatedRange);
IConditionalFormat conditionalFormat = xcfs1.AddTimePeriodCondition(TimePeriodType.Last7Days);
conditionalFormat.BackColor = Color.Orange;
//Save the file
workbook.SaveToFile("ConditionallyFormatDates.xlsx", ExcelVersion.Version2013);
}
}
}
Apply Transparency to Text in PowerPoint in C#, VB.NET
It is possible to add text transparency to any text shape in PowerPoint. In order to make the text transparent, we’d need to apply the transparency level to the text shape. This article will show you how to set the transparency level of text using Spire.Presentation.
Step 1: Create a Presentation instance.
Presentation ppt = new Presentation();
Step 2: Add a shape to the first slide.
IAutoShape textboxShape = ppt.Slides[0].Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(50, 70,300, 120)); textboxShape.ShapeStyle.LineColor.Color = Color.Transparent; textboxShape.Fill.FillType = FillFormatType.None;
Step 3: Add text to shape.
textboxShape.TextFrame.Text = "Text Transparency";
Step 4: Set the fill type of TextRange to solid, and fill the TextRange using the color created with specified alpha value.
textboxShape.TextFrame.TextRange.Fill.FillType = FillFormatType.Solid; int alpha = 55; textboxShape.TextFrame.TextRange.Fill.SolidColor.Color = Color.FromArgb(alpha, Color.Purple);
Step 5:Save the file.
ppt.SaveToFile("result.pptx", FileFormat.Pptx2013);
Output:

Full Code:
using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.Drawing;
namespace ApplyTransparency
{
class Program
{
static void Main(string[] args)
{
//create a PowerPoint document
Presentation ppt = new Presentation();
ppt.SlideSize.Type = SlideSizeType.Screen16x9;
//add a shape
IAutoShape textboxShape = ppt.Slides[0].Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(50, 70, 300, 120));
textboxShape.ShapeStyle.LineColor.Color = Color.Transparent;
textboxShape.Fill.FillType = FillFormatType.None;
//remove default blank paragraphs
textboxShape.TextFrame.Paragraphs.Clear();
//add three paragraphs, apply color with different alpha values to text
int alpha = 55;
for (int i = 0; i < 3; i++)
{
textboxShape.TextFrame.Paragraphs.Append(new TextParagraph());
textboxShape.TextFrame.Paragraphs[i].TextRanges.Append(new TextRange("Text Transparency"));
textboxShape.TextFrame.Paragraphs[i].TextRanges[0].Fill.FillType = FillFormatType.Solid;
textboxShape.TextFrame.Paragraphs[i].TextRanges[0].Fill.SolidColor.Color = Color.FromArgb(alpha, Color.Purple);
alpha += 100;
}
//save to file
ppt.SaveToFile("result.pptx", FileFormat.Pptx2013);
}
}
}
Imports Spire.Presentation
Imports Spire.Presentation.Drawing
Imports System.Drawing
Namespace ApplyTransparency
Class Program
Private Shared Sub Main(args As String())
'create a PowerPoint document
Dim ppt As New Presentation()
ppt.SlideSize.Type = SlideSizeType.Screen16x9
'add a shape
Dim textboxShape As IAutoShape = ppt.Slides(0).Shapes.AppendShape(ShapeType.Rectangle, New RectangleF(50, 70, 300, 120))
textboxShape.ShapeStyle.LineColor.Color = Color.Transparent
textboxShape.Fill.FillType = FillFormatType.None
'remove default blank paragraphs
textboxShape.TextFrame.Paragraphs.Clear()
'add three paragraphs, apply color with different alpha values to text
Dim alpha As Integer = 55
For i As Integer = 0 To 2
textboxShape.TextFrame.Paragraphs.Append(New TextParagraph())
textboxShape.TextFrame.Paragraphs(i).TextRanges.Append(New TextRange("Text Transparency"))
textboxShape.TextFrame.Paragraphs(i).TextRanges(0).Fill.FillType = FillFormatType.Solid
textboxShape.TextFrame.Paragraphs(i).TextRanges(0).Fill.SolidColor.Color = Color.FromArgb(alpha, Color.Purple)
alpha += 100
Next
'save to file
ppt.SaveToFile("result.pptx", FileFormat.Pptx2013)
End Sub
End Class
End Namespace
Set text style in word document
using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NPOI
{
class Program
{
static void Main(string[] args)
{
//Create document
XWPFDocument doc = new XWPFDocument();
//Create paragraph
XWPFParagraph para1 = doc.CreateParagraph();
para1.Alignment = ParagraphAlignment.CENTER;
//Set style of the paragraph text
XWPFRun run1 = para1.CreateRun();
run1.SetColor("Blue");
run1.FontSize = 18;
run1.SetText("This is the first paragraph");
run1.SetBold(true);
XWPFParagraph para2 = doc.CreateParagraph();
para2.Alignment = ParagraphAlignment.LEFT;
para2.BorderTop = Borders.WAVE;
XWPFRun run2 = para2.CreateRun();
run2.Subscript = VerticalAlign.BASELINE;
run2.SetColor("Red");
run2.IsItalic = true;
run2.SetUnderline(UnderlinePatterns.Dash);
run2.SetText("This is the second paragraph");
//Save the file
using (FileStream file = File.Create("TextStyle.docx"))
{
doc.Write(file);
}
//Launch
System.Diagnostics.Process.Start("TextStyle.docx");
}
}
}
Insert image in word document
using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NPOI
{
class Program
{
static void Main(string[] args)
{
//Create document
XWPFDocument doc = new XWPFDocument();
XWPFParagraph para = doc.CreateParagraph();
XWPFRun run = para.CreateRun();
//Insert image and set its size
using (FileStream picFile = new FileStream("../../../Data/image.jpg", FileMode.Open,FileAccess.Read))
{
run.AddPicture(picFile, (int)PictureType.PNG, "image", 300 * 12857, 168 * 12857);
}
//Save the file
using (FileStream file = File.Create("Image.docx"))
{
doc.Write(file);
}
//Launch
System.Diagnostics.Process.Start("Image.docx");
}
}
}
Create table in word document
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.XWPF.UserModel;
using System.IO;
namespace NPOI
{
class Program
{
static void Main(string[] args)
{
//Create document
XWPFDocument doc = new XWPFDocument();
//Create table
int row = 3;
int col = 2;
XWPFTable table = doc.CreateTable(row, col);
//Set table width
table.Width = 4000;
//Loop through the table
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
XWPFTableCell cell = table.GetRow(i).GetCell(j);
//Set style of the table
XWPFParagraph para=cell.AddParagraph();
XWPFRun run=para.CreateRun();
run.SetBold(true);
run.FontFamily = "NSimSun";
run.SetText("Row" + i + " " + "Col" + j);
table.GetRow(i).SetHeight(800);
para.Alignment = ParagraphAlignment.CENTER;
cell.SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
}
}
//Save the file
FileStream file = new FileStream("Table.docx", FileMode.Create);
doc.Write(file);
file.Close();
//Launch
System.Diagnostics.Process.Start("Table.docx");
}
}
}