How to Convert TXT to Word or Word to TXT with Java Code

Plain text (.txt) files are simple and widely used, but they lack formatting and structure. If you need to enhance a TXT file with headings, fonts, tables, or images, converting it to a Word (.docx) file is a great solution.
In this tutorial, you'll learn how to convert a .txt file to a .docx Word document in Java using Spire.Doc for Java — a powerful library for Word document processing.
Why choose Spire.Doc for Java:
- The converted Word document preserves the line breaks and content from the TXT file.
- You can further modify fonts, add styles, or insert images using Spire.Doc's rich formatting APIs.
- Supported various output formats, including converting Word to PDF, Excel, TIFF, PostScript, etc.
Prerequisites
To convert TXT to Word with Spire.Doc for Java smoothly, you should download it from its official download page and add the Spire.Doc.jar file as a dependency in your Java program.
If you are using Maven, you can easily import the JAR file by adding the following code to your project's pom.xml file:
<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.doc</artifactId>
<version>13.6.2</version>
</dependency>
</dependencies>
Steps to Convert TXT to Word in Java
Now let's take a look at how to implement it in code. With Spire.Doc for Java, the process is straightforward. You can complete the conversion with just a few lines — no need for manual formatting or additional dependencies.
To help you better understand the code:
- Document is the core class that acts as an in-memory representation of a Word document.
- loadFromFile() uses internal parsers to read .txt content and wrap it into a single Word section with default font and margins.
- When saveToFile() is called, Spire.Doc automatically converts the plain text into a .docx file by generating a structured Word document in the OpenXML format.
Below is a step-by-step code example to help you get started quickly:
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
public class ConvertTextToWord {
public static void main(String[] args) {
// Create a Text object
Document txt = new Document();
// Load a Word document
txt.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.txt");
// Save the document to Word
txt.saveToFile("ToWord.docx", FileFormat.Docx);
// Dispose resources
doc.dispose();
}
}
RESULT:

Tip:
After converting TXT files to DOC/DOCX, you can further customize the document's formatting as needed. To simplify this process, Spire.Doc for Java provides built-in support for editing text properties such as changing font color, inserting footnote, adding text and image watermark, etc.
How to Convert Word to TXT with Java
Except for TXT to Word conversion, Spire.Doc for Java also supports converting DOC/DOCX files to TXT format, making it easy to extract plain text from richly formatted Word documents. This functionality is especially useful when you need to strip out styling and layout to work with clean, raw content — such as for text analysis, search indexing, archiving, or importing into other systems that only support plain text.
Simply copy the code below and run the code to manage conversion:
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
public class ConvertWordtoText {
public static void main(String[] args) {
// Create a Doc object
Document doc = new Document();
// Load a Word document
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.doc");
// Save the document to Word
doc.saveToFile("ToText.txt", FileFormat.Txt);
// Dispose resources
doc.dispose();
}
}
RESULT:

Get a Free License
To remove evaluation watermarks and unlock full features, you can request a free 30-day license.
Conclusion
With Spire.Doc for Java, converting TXT to Word is fast, accurate, and doesn't require Microsoft Word to be installed. This is especially useful for Java developers working on reporting, document generation, or file conversion tools. Don't hesitate and give it a try now.
Send Email in C# via SMTP – HTML Format and File Attachment

Sending emails from a C# application is a common task in business and enterprise development. Whether you're delivering a project update, sending alerts, or automating reporting workflows, reliable email functionality is essential.
In this article, we’ll walk through how to send emails in C# using Spire.Email for .NET, a powerful component that simplifies SMTP communication and email formatting. We'll explore SMTP configuration, Gmail integration, HTML and plain-text content, file attachments, and multiple recipients.
Table of Contents
- 1. Project Setup
- 2. Send a Plain-Text Email via SMTP
- 3. Send HTML Email with Attachments via Gmail SMTP
- 4. Advanced Email Features with Spire.Email
- 5. Common Errors and Troubleshooting
- 6. Use Cases for Spire.Email
- 7. Free License
- 8. FAQ
1. Project Setup
To begin, create a .NET project (Console App or ASP.NET) and add the Spire.Email for .NET package.
Install via NuGet:
Install-Package Spire.Email
Or manually download the Spire.Email package and reference the Spire.Email.dll from your local installation package.
2. Send a Basic Email via SMTP in C#
The example below shows how to use Spire.Email to send a plain-text email through an SMTP server.
using Spire.Email;
using Spire.Email.Smtp;
// Configure the SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.example.com";
smtp.Port = 587;
smtp.Username = "your@example.com";
smtp.Password = "your_password";
smtp.ConnectionProtocols = ConnectionProtocols.StartTls;
// Create maill addresses
MailAddress sender = new MailAddress("your@example.com", "Sender Name");
MailAddress recipient = new MailAddress("recipient@example.com", "Recipient Name");
MailMessage message = new MailMessage(sender, recipient);
// Set the email content
message.Subject = "Test Email";
message.BodyText = "This is a plain-text test email.";
// Send the email
smtp.SendOne(message);
Explanation:
- Uses MailAddress and MailMessage from Spire.Email
- Establishes a secure SMTP connection using ConnectionProtocols.StartTls
The screenshot below shows the actual email received using the above SMTP code.

3. Send HTML Email with Attachments via Gmail SMTP in C#
The following C# code example demonstrates how to send an HTML-formatted email using Gmail SMTP, including multiple recipients, a file attachment, and plain-text fallback for clients that do not support HTML.
using Spire.Email;
using Spire.Email.Smtp;
// Create MailAddress objects
MailAddress from = new MailAddress("your@gmail.com", "Your Name");
MailAddress to1 = new MailAddress("user1@example.com", "User One");
MailAddress to2 = new MailAddress("user2@example.com", "User Two");
// Create a mail message
MailMessage message = new MailMessage(from, to1);
message.To.Add(to2);
message.Cc.Add(new MailAddress("cc@example.com", "CC Person"));
message.Bcc.Add(new MailAddress("bcc@example.com"));
// Set the body HTML and text for the message
message.Subject = "Monthly Report - June 2025";
message.BodyHtml = "<h2 style='color:#2E86C1;'>Report Summary</h2><p>Please see the attached PDF report.</p>";
message.BodyText = "Report Summary - please see the attached PDF.";
// Add an attachment to the email
Attachment attachment = new Attachment(@"Sample.pdf");
message.Attachments.Add(attachment);
// Configure the SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Username = "your@gmail.com";
smtp.Password = "your_app_password";
smtp.ConnectionProtocols = ConnectionProtocols.StartTls;
// Sen the email
smtp.SendOne(message);
Explanation:
- Uses MailAddress, MailMessage, Attachment, and SmtpClient from Spire.Email
- Combines BodyHtml and BodyText to support HTML and plain-text email clients
- Adds multiple recipients via To.Add(), Cc.Add(), and Bcc.Add()
- Sends email securely through Gmail using ConnectionProtocols.StartTls
Gmail requires App Passwords if 2FA is enabled.
The following screenshot shows the HTML-formatted email with rich text, CC and BCC recipients, and a PDF attachment, as received from Gmail SMTP.

Related article: How to Send an Email with Attachments in C#
4. Advanced Email Features with Spire.Email
This section demonstrates advanced C# email-sending capabilities using Spire.Email, including embedded images and batch dispatch.
// Prepare an email with embedded image
MailMessage message = new MailMessage(
new MailAddress("your@domain.com", "Sender"),
new MailAddress("client@domain.com", "Client"));
message.Subject = "Branding Update";
message.BodyHtml = "<h1>Our New Logo</h1><img src=\"cid:logo\">";
message.BodyText = "Please view this message in HTML to see the image.";
Attachment logo = new Attachment(@"C:\Images\logo.png");
logo.ContentId = "logo";
logo.DispositionType = "Inline";
message.Attachments.Add(logo);
// Prepare a second email
MailMessage message2 = new MailMessage(
new MailAddress("your@domain.com"),
new MailAddress("sales@domain.com"));
message2.Subject = "Weekly Summary";
message2.BodyText = "This is an automated weekly update.";
// Create SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.domain.com";
smtp.Port = 587;
smtp.Username = "your@domain.com";
smtp.Password = "your_password";
smtp.ConnectionProtocols = ConnectionProtocols.StartTls;
// Send one email
smtp.SendOne(message);
// Send emails in batch
smtp.SendSome(new List<MailMessage> { message, message2 });
Explanation:
Attachment.ContentIdandDispositionType = "Inline"allow inline images using CID references in HTML.SendOne()sends a single message.SendSome()sends multiple messages as a batch. Ideal for scheduled reports or group notifications.
The following screenshot shows an email with an embedded company logo and a plain-text fallback, demonstrating how Spire.Email renders HTML content with inline images.

You may also like: Creating MSG Files with RTF Body and Attachments Using C#
5. Common Errors and Troubleshooting
| Error | Likely Cause |
|---|---|
| Authentication failed | Incorrect credentials or missing app password |
| Secure connection required | Use StartTLS or SSL in ConnectionProtocols |
| HTML content not displaying | Ensure BodyHtml and fallback BodyText are set |
| File not found | Incorrect file path for attachment |
6. Use Cases for Spire.Email
Spire.Email for .NET is suitable for:
- Daily/weekly automated reporting
- User signup and notification emails
- Order confirmations with attachments
- Form submission alerts
- Embedded-image newsletters
Its clean API removes the need to manually handle SMTP headers, MIME formatting, and encoding issues.
Conclusion
With Spire.Email for .NET, developers can quickly build robust and flexible email-sending features directly into C# applications. Whether the goal is to deliver transactional messages, generate styled reports, or dispatch scheduled newsletters, this component provides a clean, reliable API that simplifies every step of the process.
By supporting plain-text and HTML formats, attachments, Gmail SMTP, embedded images, and batch sending, Spire.Email helps streamline email integration without the overhead of external dependencies.
7. Apply for a Free Temporary License
To remove the evaluation warning in the email body or attachment footer, you can apply for a free temporary license:
Request a Free 1-Month License
Simply fill out the form and follow the instructions to apply the license in your project. This enables full feature access during evaluation.
8. FAQ
How to send HTML email in C#?
You can set the BodyHtml property of the MailMessage object to send an HTML email using Spire.Email. You can also include BodyText as a fallback for clients that don't support HTML.
How to send email to multiple recipients in C#?
Add multiple recipients using message.To.Add(), message.Cc.Add(), and message.Bcc.Add() methods. Spire.Email supports To, Cc, and Bcc fields.
How to use SMTP to send email in ASP.NET or MVC projects?
The SMTP usage in ASP.NET or MVC is the same as in Console applications. Simply configure the SmtpClient with host, port, credentials, and use the same SendOne() or SendSome() methods to dispatch your message.
How to Read Barcodes in Python: From Image Files or Bytes

Modern business systems, from retail checkout lanes to warehouse inventory tracking, rely heavily on barcode scanning, and Python-based solutions have become a popular choice due to their versatility and ease of use. In this article, we’ll explore how to read barcodes in Python using the Spire.Barcode for Python library, covering setup, scanning from image files or bytes, and customization options for improved accuracy.
Table of Contents:
- Python Library for Reading Barcodes
- Integrate Spire.Barcode into Your Python Application
- Read a Barcode from an Image File
- Read Multiple Barcodes from an Image File
- Read Barcodes from Image Bytes
- Adjust Barcode Recognition Settings
- Conclusion
- FAQs
Python Library for Reading Barcodes
Spire.Barcode for Python is a powerful library specifically crafted for creating and reading barcodes in Python applications. The library supports a variety of barcode formats, including:
- 1D Barcodes : Such as Code 128, Code 39, EAN-13, and UPC-A.
- 2D Barcodes : Including QR Code, DataMatrix, and PDF417.
Notable Features of Spire.Barcode
- Format Support : Capable of reading barcodes from various image formats, including PNG, JPG, BMP, GIF, and TIFF.
- Batch Scanning : Enables the detection of multiple barcodes within a single image file.
- Recognition Accuracy : Utilizes advanced algorithms to deliver reliable barcode detection.
- Customization : Allows users to specify barcode types and enable checksum verification for enhanced recognition efficiency.
This library provides the capability to read barcodes from both image files and bytes, along with extensive customization options to meet diverse requirements.
Integrate Spire.Barcode into Your Python Application
To get started with Spire.Barcode, you first need to install the library. You can do this via pip. Open your terminal and run:
pip install spire.barcode
Once you have installed the library, you will need a license key to unlock its full capabilities. You can obtain a trial license from our website. and set up the library in your Python script:
from spire.barcode import *
License.SetLicenseKey("your license key")
Now that you have the library in place, you can begin reading barcodes using Python.
Read a Barcode from an Image File in Python
Reading a single barcode from an image file is straightforward with Spire.Barcode. Here's how you can do it:
from spire.barcode import *
# Apply license key to unlock full capabilities
License.SetLicenseKey("your license key")
# Read barcode from an image file
result = BarcodeScanner.ScanOneFile("C:/Users/Administrator/Desktop/qr_code.png")
# Print the result
print(result)
Explanation
- License.SetLicenseKey() : Initializes the library with your license key.
- BarcodeScanner.ScanOneFile() : Reads a single barcode from the specified image file.
- The result is printed to the console, displaying the barcode's data.
Output:

Read Multiple Barcodes from an Image File in Python
If you need to read multiple barcodes from a single image file, Spire.Barcode makes this easy as well. Here’s an example:
from spire.barcode import *
# Apply license key to unlock full capabilities
License.SetLicenseKey("your license key")
# Read multiple barcodes from stream
results = BarcodeScanner.ScanFile("C:/Users/Administrator/Desktop/barcodes.jpg")
# Print results
print(results)
Explanation
- BarcodeScanner.ScanFile() : Scans the entire image for multiple barcodes.
- The results are stored as a list. Each element in the list contains the data from a detected barcode.
Output:

Read Barcodes from Image Bytes in Python
In addition to reading barcodes directly from files, Spire.Barcode for Python supports decoding barcodes from in-memory image bytes . This approach is useful when working with dynamically loaded images (e.g., from APIs, databases, or user uploads).
Here’s how to do it:
from spire.barcode import *
# Apply license key to unlock full capabilities
License.SetLicenseKey("your license key")
# Read an image file into bytes
image_path = "C:/Users/Administrator/Desktop/barcodes.jpg"
with open(image_path, "rb") as file:
image_bytes = file.read()
# Wrap bytes in Spire.Barcode's Stream object
stream = Stream(image_bytes)
# Read one barcode from stream
# result = BarcodeScanner.ScanOneStream(stream)
# Read multiple barcodes from stream
results = BarcodeScanner.ScanStream(stream)
# Print results
print(results)
Explanation
- image_bytes: Raw binary data read from an image file (e.g., PNG, JPG) or other sources like APIs or databases.
- Stream (Spire.Barcode class): Converts image_bytes into an in-memory stream compatible with Spire.Barcode’s scanner.
- BarcodeScanner.ScanStream() : Scans the stream for barcodes and returns a list of detected barcodes.
Adjust Barcode Recognition Settings
The BarcodeScanner class provides various methods to customize barcode recognition settings. This can help improve detection accuracy and efficiency. Some of the key methods include:
- ScanOneFileBarCodeTypeIncludeCheckSum(fileName: str, barcodeType: BarCodeType, IncludeCheckSum: bool)
- ScanFileBarCodeTypeIncludeCheckSum(fileName: str, barcodeType: BarCodeType, IncludeCheckSum: bool)
- ScanOneStreamBarCodeTypeIncludeCheckSum(stream: Stream, barcodeType: BarCodeType, IncludeCheckSum: bool)
- ScanStreamBarCodeTypeIncludeCheckSum(stream: Stream, barcodeType: BarCodeType, IncludeCheckSum: bool)
Here’s an example of how to specify a barcode type and include checksum verification:
from spire.barcode import *
# Apply license key to unlock full capabilities
License.SetLicenseKey("your license key")
# Specify the barcode type (e.g., EAN13)
barcode_type = BarCodeType.EAN13
# Read a barcode from an image file with checksum included
result = BarcodeScanner.ScanOneFileBarCodeTypeIncludeCheckSum("C:/Users/Administrator/Desktop/EAN_13.png", barcode_type, True)
# Print the result
print(result)
Explanation
- BarcodeType : Specifies the type of barcode you want to scan.
- IncludeCheckSum (bool): Determines whether to verify the checksum during scanning. Setting it to True can help catch errors in data.
Conclusion
In this article, we explored how to read barcodes in Python using the Spire.Barcode library. We covered the setup process, reading single and multiple barcodes from image files, and reading from image bytes. Additionally, we discussed how to customize barcode detection settings for improved accuracy. With these tools at your disposal, you can easily integrate barcode scanning capabilities into your Python applications.
FAQs
Q1: What types of barcodes can I read with Spire.Barcode?
Spire.Barcode supports a wide range of barcode formats, including QR codes, UPC, EAN, Code 128, Code 39, and many others.
Q2: Do I need a license to use Spire.Barcode?
Yes, a license key is required to unlock the full functionality of the library. You can obtain a free 30-day trial license from our website.
Q3: Can I read barcodes from a webcam using Spire.Barcode?
While Spire.Barcode does not directly support webcam input, you can capture images from a webcam and then read barcodes from those images using the library.
Q4: How can I improve barcode scanning accuracy?
You can improve accuracy by specifying the barcode type and enabling checksum verification during scanning. Additionally, ensure that the images are clear and well-lit.
Q5. Can I generate barcodes using Spire.Barcode for Python?
Yes, Spire.Barcode supports both barcode recognition and generation. For detailed instructions, check out this tutorial: How to Generate Barcodes in Python: A Step-by-Step Guide.
How to Read QR Code in C# – From Image or Stream

QR codes have become a common part of modern applications — from user authentication and digital payments to product packaging and event tickets. In many of these scenarios, developers often need to read QR codes in C# as part of their workflow, especially when working with image-based inputs like scanned documents or uploaded files.
To handle such tasks reliably, a decoding method that’s both accurate and easy to implement is essential. In this tutorial, we’ll walk through a straightforward approach to reading QR codes from images using C#, with minimal setup and clean integration.
Quick Navigation
- Project Setup
- Read QR Code from Image Using C#
- Read QR Code from Stream Using C#
- Improve Accuracy and Handle Errors
- Bonus: Get QR Code Coordinates
- FAQ
- Final Thoughts
1. Project Setup
To begin, we’ll use a .NET barcode library that supports QR code decoding. In this guide, we demonstrate with Spire.Barcode for .NET, which provides a simple API for reading QR codes from image files and streams.
1.1 Install the Library via NuGet
You can install the library through NuGet Package Manager:
Install-Package Spire.Barcode
For basic scenarios, you can also use Free Spire.Barcode for .NET:
Install-Package FreeSpire.Barcode
1.2 Create a New Console Project
For demonstration, create a C# Console App in Visual Studio:
- Target .NET Framework, .NET Core/.NET 6+, ASP.NET, or Xamarin for cross-platform mobile development
- Add reference to Spire.Barcode.dll (if not using NuGet)
2. Read QR Code from Image in C#
To read QR codes from an image file in C#, you can simply use the static BarcodeScanner.Scan() method provided by the library. This method takes an image path and the BarCodeType as input and returns all decoded results that match the specified barcode type — in this case, QR codes.
This method supports scanning images in formats like JPG, PNG, and EMF. It’s the most direct way to scan QR code data in desktop applications or backend services that receive uploaded files.
2.1 Sample Code: Decode QR Code from an Image File
using Spire.Barcode;
class Program
{
static void Main(string[] args)
{
// Load the QR code image
string imagePath = @"C:\qr-code.png";
// Barcode scanner reads QR code from image file
string[] results = BarcodeScanner.Scan(imagePath, BarCodeType.QRCode);
// Display QR code result(s)
foreach (string result in results)
{
Console.WriteLine("QR Code Data: " + result + "\n");
}
}
}
The QR code image and the scan results from C# code:

2.2 Explanation
- Scan() reads and decodes all barcodes found in the image.
- BarCodeType.QRCode ensures only QR codes are detected (you can change it to detect other types).
- Returns an array in case the image contains multiple QR codes.
You may also like: How to Generate QR Codes Using C#
3. Read QR Code from Stream in C#
In web APIs or modern applications where images are processed in memory, you’ll often deal with Stream objects—such as when handling file uploads or reading from cloud storage.
The BarcodeScanner.Scan() method also accepts a Stream directly, allowing you to decode QR codes from memory streams without converting them to Bitmap.
using Spire.Barcode;
using System.IO;
class Program
{
static void Main(string[] args)
{
using (FileStream fs = new FileStream(@"C:\qr-code.png", FileMode.Open, FileAccess.Read))
{
// Directly scan the QR codes from the image stream
string[] results = BarcodeScanner.Scan(fs, BarCodeType.QRCode, false);
foreach (string result in results)
{
Console.WriteLine("QR Code Data: " + result);
}
}
}
}
This method is useful for WPF or ASP.NET Core apps that handle QR code images in memory.
Related article: Scan Barcodes from PDF Using C#
4. Improve Accuracy and Handle Errors
In real-world scenarios, QR code recognition may occasionally fail due to image quality or unexpected input issues. Here are best practices to improve decoding accuracy and handle failures in C#:
4.1 Boost Recognition Accuracy
- Use high-resolution images. Avoid blurred or overcompressed files.
- Ensure quiet zone (white space) around the QR code is preserved.
- Use formats like PNG for better clarity.
- Avoid perspective distortion — use straight, scanned images.
4.2 Add Robust Error Handling
Wrap your decoding logic in a try-catch block to prevent crashes and inform the user clearly:
try
{
string[] results = BarcodeScanner.Scan(imagePath, BarCodeType.QRCode);
if (results.Length == 0)
{
Console.WriteLine("No QR code found.");
}
else
{
Console.WriteLine("QR Code: " + results[0]);
}
}
catch (Exception ex)
{
Console.WriteLine("Error decoding QR code: " + ex.Message);
}
5. Bonus: Get QR Code Coordinates
Sometimes, you may need to locate the QR code’s exact position in the image—for cropping, overlay, or annotation. The ScanInfo() method helps retrieve bounding boxes:
BarcodeInfo[] results = BarcodeScanner.ScanInfo(imagePath, BarCodeType.QRCode);
foreach (BarcodeInfo result in results)
{
Console.WriteLine("Data: " + result.DataString);
Console.WriteLine($"Coordinates: " + string.Join(",", result.Vertexes.Select(p => $"({p.X},{p.Y})")) + "\n");
}
This provides both the data and the coordinates of each detected QR code.
The reading results:

6. FAQ
How to read QR code in C#?
You can use the Spire.Barcode for .NET library and its BarcodeScanner.Scan() method to read QR codes from image files or memory streams in just a few lines of code.
How do I read my own QR code image?
Load your QR code image file path into the scanner, or open it as a stream if you're working in a web or WPF application. The scanner will decode all readable QR codes in the image.
How to read barcodes in C# (not just QR codes)?
You can simply pass the image path to the Scan() method, and it will automatically detect and read all supported barcode types. To restrict detection to a specific type (e.g., only QR codes or Code128), pass the corresponding BarCodeType as the second parameter.
What is the best barcode reader library for C#?
Spire.Barcode for .NET is a popular choice for its simplicity, format support, and clean API. It supports both free and commercial use cases.
7. Final Thoughts
Reading QR codes in C# can be implemented with just a few lines of code using Spire.Barcode for .NET. It supports image and stream-based decoding, works well for desktop, server-side, or WPF applications, and offers solid performance with minimal setup.
You can further explore QR code generation, document integration, and real-time scanning workflows based on this foundation.
Need to unlock full barcode reading features?
Request a free temporary license and try the full capabilities of Spire.Barcode for .NET without limitations.
How to Read Barcodes in Java Using Spire.Bacode

Barcodes are widely used in various industries for inventory management, retail, logistics, and more. Reading barcodes efficiently is crucial for automating data entry and improving accuracy. In Java, one of the most reliable libraries for barcode recognition is Spire.Barcode for Java. This article provides a comprehensive guide on how to read barcode in Java using this powerful library.
Table of Contents
- Introduction to Spire.Barcode for Java
- Key Features of Spire.Barcode
- Setting Up Spire.Barcode in Your Java Project
- Reading a Single Barcode from an Image File
- Reading Multiple Barcodes from One Image
- Customizing Barcode Recognition Settings
- Conclusion
- FAQs
Introduction to Spire.Barcode for Java
Spire.Barcode for Java is a robust library designed to generate and read barcodes in Java applications. It supports a wide range of barcode symbologies, including:
- 1D Barcodes : Code 128, Code 39, EAN-13, UPC-A, etc.
- 2D Barcodes : QR Code, DataMatrix, PDF417, etc.
Spire.Barcode provides fast and precise barcode recognition in Java, whether scanning from a dedicated barcode image or a complex image containing additional elements.
Key Features of Spire.Barcode
Before diving into implementation, let’s explore some key features of Spire.Barcode:
- Multi-Format Support : Read barcodes from PNG, JPG, BMP, GIF, and TIFF images.
- Batch Processing : Scan multiple barcodes in a single image.
- High Recognition Accuracy : Advanced algorithms ensure reliable barcode detection.
- Customizable Settings : Adjust scan regions and barcode types for optimized recognition.
- Cross-Platform Compatibility : Works seamlessly on Windows, Linux, and macOS.
These features make Spire.Barcode an excellent choice for enterprise-level barcode processing.
Setting Up Spire.Barcode in Your Java Project
To start reading barcodes in Java, you need to integrate Spire.Barcode into your project. Follow these steps:
Step 1: Install the Library
If you're using Maven, you can easily integrate Spire.Barcode by adding the following dependency to your pom.xml file:
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.barcode</artifactId>
<version>5.1.11</version>
</dependency>
For manual setup, download Spire.Barcode for Java from our website and add the downloaded .jar file to your project’s build path.
Step 2: Get a Temporary License
Spire.Barcode requires a license to read certain barcode types. To unlock full barcode recognition capabilities, get a free 30-day trial license. After receiving the license file, apply it using this code:
LicenseProvider.setLicenseKey("your license key");
Now, you're ready to read barcode in Java using Spire.Barcode.
Reading a Single Barcode from an Image File
Reading one barcode from an image is a fundamental scenario, and Spire.Barcode facilitates this with just a few lines of code.
Here’s a step-by-step example:
import com.spire.barcode.BarcodeScanner;
import com.spire.barcode.license.LicenseProvider;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ReadBarcode {
public static void main(String[] args) throws IOException {
// Apply license key to remove restrictions on barcode types
LicenseProvider.setLicenseKey("your license key");
// Load the image file containing the barcode
BufferedImage bufferedImage = ImageIO.read(new File("C:\\Users\\Administrator\\Desktop\\barcode.jpg "));
// Scan the barcode from the loaded image
String result = BarcodeScanner.scanOne(bufferedImage);
// Output the scanned barcode result
System.out.print(result);
}
}
Explanation
- ImageIO.read() loads the image file, supporting extensions such as .png, .jpeg, .bmp, or .gif.
- BarcodeScanner.scanOne() detects and decodes the barcode from the image.
- The decoded result is stored in a String .
Note
The scanOne() method and the scan() method, which will be discussed later, can accept not only a BufferedImage as a parameter but also an InputStream and a String representing the image file path. Whether you're processing images from disk, user uploads, or real-time streams, this flexibility simplifies integration into diverse workflows.
Output:

Reading Multiple Barcodes from One Image
Spire.Barcode can detect and decode multiple barcodes in a single image. Here’s how:
import com.spire.barcode.BarcodeScanner;
import com.spire.barcode.license.LicenseProvider;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
public class ReadMultipleBarcodes {
public static void main(String[] args) throws IOException {
// Apply license key to remove restrictions on barcode types
LicenseProvider.setLicenseKey("your license key");
// Load the image file containing the barcode
BufferedImage bufferedImage = ImageIO.read(new File("C:\\Users\\Administrator\\Desktop\\barcodes.jpg"));
// Scan the barcode from the loaded image
String[] results = BarcodeScanner.scan(bufferedImage);
// Output the results
System.out.println(Arrays.toString(results));
}
}
Explanation
- BarcodeScanner.scan() identifies and decodes all the barcodes present in the image.
- The results are stored in a String array .
Output:

Customizing Barcode Recognition Settings
For improved accuracy, Spire.Barcode allows you to customize scan settings, such as defining a scan region or specifying a particular barcode type. This enhanced approach ensures you have the flexibility and control needed for effective barcode scanning in Java.
Here is an example:
import com.spire.barcode.BarCodeType;
import com.spire.barcode.BarcodeScanner;
import com.spire.barcode.license.LicenseProvider;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class CustomScanSettings {
public static void main(String[] args) throws IOException {
// Apply license key to remove restrictions on barcode types
LicenseProvider.setLicenseKey("your license key");
// Load the image file containing the barcode
BufferedImage bufferedImage = ImageIO.read(new File("C:\\Users\\Administrator\\Desktop\\barcodes.jpg"));
// Define a rectangle area for barcode recognition
Rectangle rectangle = new Rectangle(0,0,380,270);
// Scan the barcode from the loaded image
String[] results = BarcodeScanner.scan(bufferedImage, rectangle, BarCodeType.Code_93);
// Output the first result
System.out.print(results[0]);
}
}
Explanation
- Rectangle() defines a specific area within the image for barcode recognition.
- BarCodeType enumeration allows you to specify the barcode type for more accurate detection.
Output:

Conclusion
In this article, we've explored the essential steps to set up Spire.Barcode in your Java project, read barcodes from images , handle multiple barcodes , and customize recognition settings for optimal accuracy. By leveraging these capabilities, developers can seamlessly integrate barcode scanning into their applications, improving data entry automation and reducing errors.
With Spire.Barcode, you have a reliable tool at your disposal to meet your barcode reading needs, paving the way for more efficient business operations.
FAQs
Q1. What types of barcodes can Spire.Barcode read?
Spire.Barcode supports 38+ barcode types, including both 1D barcodes like Code 128, Code 39, EAN-13, and UPC-A, as well as 2D barcodes such as QR Code, DataMatrix, and PDF417.
Q2. Can I customize the barcode scanning region?
Yes, Spire.Barcode allows you to define a specific scan area within the image by using a Rectangle object. This feature helps improve accuracy by focusing on a designated section of the image.
Q3. Can Spire.Barcode read multiple barcodes from a single image?
Yes! Using BarcodeScanner.scan(), you can detect and decode multiple barcodes in one image efficiently.
Q4. Is a license required to use Spire.Barcode for barcode recognition?
A commercial license is needed for full functionality, but you can get a free 30-day trial license to test all features before purchasing.
Q5. Can I use Spire.Barcode for Java to create barcodes?
Yes, Spire.Barcode supports generating over 38 commonly used 1D and 2D barcodes. For more information, check out: How to Create Barcode in Java
Spire.Office for Java 10.6.0 is released
We are excited to announce the release of Spire.Office for Java 10.6.0. In this version, Spire.Doc for Java adds support for reading and setting chart formats; Spire.XLS for Java supports using font streams when applying custom fonts; and Spire.Presentation for Java enables copying formulas within paragraphs. In addition, many known issues have been successfully resolved. More details are provided below.
Here is a list of changes made in this release
Spire.Doc for Java
| Category | ID | Description |
| New feature | - | Supports getting and setting chart formats, including chart titles, data labels, axes, legends, and data tables. |
| New feature | - | Optimizes the reading and setting of table formats. |
| New feature | - | Optimizes Word-to-PDF conversion performance, reducing processing time and memory usage. |
| Bug | SPIREDOC-10375 | Fixes the issue where TOC (Table of Contents) field updates failed. |
| Bug | SPIREDOC-10582 SPIREDOC-11284 |
Fixes the issue where the “outputToOneSvg” parameter did not take effect during Word-to-SVG conversion. |
| Bug | SPIREDOC-10792 SPIREDOC-11165 |
Fixes the "Key cannot be null" error when comparing Word documents. |
| Bug | SPIREDOC-11237 | Fixes the "Cannot insert an object of type 10 into the 6" error when comparing Word documents. |
| Bug | SPIREDOC-11247 | Fixes blank content issues when comparing Word documents. |
| Bug | SPIREDOC-11264 | Fixes incorrect content retrieval when calling getText(). |
| Bug | SPIREDOC-11281 | Fixes incorrect line styles when accepting revisions. |
Spire.XLS for Java
| Category | ID | Description |
| New feature | SPIREXLS-5817 | Added support for font stream data when applying custom fonts.
Workbook book = new Workbook();
FileInputStream stream = new FileInputStream("fontpath");
book.setCustomFontStreams(new FileInputStream[]{stream});
|
| New feature | SPIREXLS-5821 | Added support for setting setIsSaveBlankCell to control whether to export extra blank cells when converting Excel to HTML.
Workbook workbook = new Workbook(); workbook.loadFromFile(inputFile); WorksheetsCollection sheets = workbook.getWorksheets(); HTMLOptions options = new HTMLOptions(); options.setImageEmbedded(true); options.setStyleDefine(HTMLOptions.StyleDefineType.Inline); options.setIsSaveBlankCell(true); |
| New feature | SPIREXLS-5822 | Added support for retrieving the cell location of embedded images.
Worksheet worksheet=wb.getWorksheets().get(0); ExcelPicture[] cellimages=worksheet.getCellImages(); cellimages[0].getEmbedCellName() |
| Bug | SPIREXLS-5522 | Fixed the issue where sheet.getCellImages() could not retrieve images inserted by Office 365. |
| Bug | SPIREXLS-5803 | Fixed the issue where page numbering was incorrect when converting Excel to PDF. |
| Bug | SPIREXLS-5812 | Fixed the issue that caused a "NullPointerException" when copying Excel and saving it as .xls. |
| Bug | SPIREXLS-5813 | Fixed the issue where text content was truncated when converting Excel to PDF. |
| Bug | SPIREXLS-5815 | Fixed the issue that caused the error "For input string: 'OP_ID'" when converting CSV to Excel. |
| Bug | SPIREXLS-5816 | Fixed the issue where autoFitColumns() behaved incorrectly. |
| Bug | SPIREXLS-5823 | Fixed the issue where cell styling was inconsistent when converting Excel to HTML with setIsFixedTableColWidth enabled. |
| Bug | SPIREXLS-5844 | Fixed the issue that caused the error "Specified argument was out of the range of valid values" when converting Excel to HTML. |
| Bug | SPIREXLS-5852 SPIREXLS-5855 |
Fixed the issue where Excel was rendered incorrectly when converting to HTML. |
Spire.PDF for Java
| Category | ID | Description |
| Bug | SPIREPDF-7485 | Fixed the issue that spaces were lost after converting PDF to PDFA3B. |
| Bug | SPIREPDF-7497 | Fixed the issue that signatures were lost after converting PDF to PDFA1A. |
| Bug | SPIREPDF-7506 | Fixed the issue that the program threw NullPointerException after converting OFD to PDF. |
| Bug | SPIREPDF-7524 | Fixed the issue that fonts were incorrect after replacing text. |
| Bug | SPIREPDF-7530 | Fixed the issue that table layouts were incorrect after creating booklets using PdfBookletCreator. |
Spire.Presentation for Java
| Category | ID | Description |
| New feature | SPIREPPT-2856 | Supports copying formulas within paragraphs.
Presentation sourcePpt = new Presentation();
sourcePpt.loadFromFile("data1.pptx");
Presentation targetPpt = new Presentation();
targetPpt.loadFromFile("data2.pptx");
copyNotes(sourcePpt.getSlides().get(0),targetPpt.getSlides().get(0));
targetPpt.saveToFile("out.pptx", com.spire.presentation.FileFormat.PPTX_2013);
public static void copyNotes(ISlide sourceSlide, ISlide targetSlide) throws DocumentEditException {
if (sourceSlide.getNotesSlide() == null) {
System.out.println(sourceSlide.getName());
return;
}
// The paragraph contains formulas
System.out.println(sourceSlide.getNotesSlide().getNotesTextFrame().getText());
ParagraphCollection paragraphs = sourceSlide.getNotesSlide().getNotesTextFrame().getParagraphs();
targetSlide.getNotesSlide().getNotesTextFrame().getParagraphs().append(paragraphs);
|
| Bug | SPIREPPT-2860 | Fixes the issue where the height of the shape decreased after adding blank paragraphs. |
| Bug | SPIREPPT-2850 SPIREPPT-2868 SPIREPPT-2869 SPIREPPT-2870 SPIREPPT-2879 SPIREPPT-2883 |
Fixed the issue where adding LaTeX formulas to PPTX files resulted in incorrect output. |
| Bug | SPIREPPT-2861 | Fixed the issue where converting ODP to PDF resulted in an “Unknown file format” error. |
| Bug | SPIREPPT-2870 | Fixed the issue where adding LaTeX formulas resulted in a “ClassCastException” error. |
| Bug | SPIREPPT-2884 | Fixed the issue where retrieving data resulted in a “NullPointerException” error. |
| Bug | SPIREPPT-2891 | Fixed the issue where adding LaTeX formulas caused an error when opening the resulting document. |
| Bug | SPIREPPT-2894 | Fixed the issue where retrieving data from a doughnut chart resulted in incorrect output. |
Spire.Presentation for Java 10.6.2 supports copying formulas within paragraphs
We are excited to announce the release of Spire.Presentation for Java 10.6.2. The latest version supports copying formulas within paragraphs. Besides, some known bugs are fixed successfully in the new version, such as the issue that the program threw an "Unknown file format" error when converting ODP to PDF. More details are listed below.
Here is a list of changes made in this release
| Category | ID | Description |
| New feature | SPIREPPT-2856 | Supports copying formulas within paragraphs.
Presentation sourcePpt = new Presentation();
sourcePpt.loadFromFile("data1.pptx");
Presentation targetPpt = new Presentation();
targetPpt.loadFromFile("data2.pptx");
copyNotes(sourcePpt.getSlides().get(0),targetPpt.getSlides().get(0));
targetPpt.saveToFile("out.pptx", com.spire.presentation.FileFormat.PPTX_2013);
public static void copyNotes(ISlide sourceSlide, ISlide targetSlide) throws DocumentEditException {
if (sourceSlide.getNotesSlide() == null) {
System.out.println(sourceSlide.getName());
return;
}
// The paragraph contains formulas
System.out.println(sourceSlide.getNotesSlide().getNotesTextFrame().getText());
ParagraphCollection paragraphs = sourceSlide.getNotesSlide().getNotesTextFrame().getParagraphs();
targetSlide.getNotesSlide().getNotesTextFrame().getParagraphs().append(paragraphs);
|
| Bug | SPIREPPT-2850 SPIREPPT-2868 SPIREPPT-2869 SPIREPPT-2870 SPIREPPT-2879 SPIREPPT-2883 |
Fixes the issue of incorrect rendering when adding LaTeX formulas to presentations. |
| Bug | SPIREPPT-2861 | Fixes the issue that the program threw an "Unknown file format" error when converting ODP to PDF. |
| Bug | SPIREPPT-2870 | Fixes the issue that the program threw a "ClassCastException" when adding LaTeX formulas. |
| Bug | SPIREPPT-2884 | Fixes the issue that the program threw a "NullPointerException" when retrieving content. |
| Bug | SPIREPPT-2891 | Fixes the issue that documents were corrupted when opening files with added LaTeX formulas. |
| Bug | SPIREPPT-2894 | Fixes the issue that data retrieval was incorrect for Doughnut Charts. |
Spire.Office 10.6.0 is released
We’re pleased to announce the release of Spire.Office for .NET 10.6.0. This version introduces three new features, for example, Spire.Doc supports setting rounded corners on rectangle shapes; Spire.XLS supports the SHEETS() function. Meanwhile, a large number of known bugs have been successfully fixed. More details are given below.
In this version, the most recent versions of Spire.Doc, Spire.PDF, Spire.XLS, Spire.Presentation, Spire.Email, Spire.DocViewer, Spire.PDFViewer, Spire.Spreadsheet, Spire.OfficeViewer, Spire.DataExport, Spire.Barcode are included.
DLL Versions:
- Spire.Doc.dll v13.6.14
- Spire.Pdf.dll v11.6.18
- Spire.XLS.dll v15.6.6
- Spire.Presentation.dll v10.6.4
- Spire.Barcode.dll v7.3.7
- Spire.Email.dll v6.6.3
- Spire.DocViewer.Forms.dll v8.9.1
- Spire.PdfViewer.Asp.dll v8.1.3
- Spire.PdfViewer.Forms.dll v8.1.3
- Spire.Spreadsheet.dll v7.5.2
- Spire.OfficeViewer.Forms.dll v8.8.0
- Spire.DataExport.dll v4.9.0
- Spire.DataExport.ResourceMgr.dll v2.1.0
Here is a list of changes made in this release
Spire.Doc
| Category | ID | Description |
| New feature | SPIREDOC-11102 | Added support for setting rounded corners on rectangle shapes.
if (Cobj is ShapeObject)
{
ShapeObject shape = (ShapeObject)Cobj;
if (shape.ShapeType == ShapeType.RoundRectangle)
{
double cornerRadius = shape.AdjustHandles.GetRoundRectangleCornerRadius();
shape.AdjustHandles.AdjustRoundRectangle(20);
}
}
|
| New feature | SPIREDOC-11335 | Added support for retrieving move revisions.
DifferRevisions differRevisions = new DifferRevions(Document) List<DocumentObject> moveRevisions = differRevisions.MoveFromRevisions; List<DocumentObject> movetoRevisions = differRevisions.MoveToRevisions; |
| Bug | SPIREDOC-11060 | Fixed the issue that the paragraph text content retrieved was incorrect. |
| Bug | SPIREDOC-11066 | Fixed the issue where the document language displayed incorrectly when ‘LocaleIdASCII’ was set to Hebrew (1037). |
| Bug | SPIREDOC-11332 | Fixed the issue where extra blank pages appeared when converting Word to PDF. |
Spire.PDF
| Category | ID | Description |
| Bug | SPIREPDF-7302 | Fixed the issue that converting PDF to images produced incorrect results. |
| Bug | SPIREPDF-7491 | Fixed the issue where the program threw an "ArgumentOutOfRangeException" error when loading a PDF file. |
| Bug | SPIREPDF-7525 | Fixed the issue where the program threw a "NullReferenceException" when calling the PdfDocument.Preview() method. |
| Bug | SPIREPDF-4390 SPIREPDF-4462 |
Fixed the issue that the Arabic text rendering effect was displayed incorrectly. |
| Bug | SPIREPDF-6586 | Fixed the issue where the content was incorrect when converting PDF to Excel. |
| Bug | SPIREPDF-7177 | Fixed the issue where the bold text styles were lost when converting PDF to Markdown. |
| Bug | SPIREPDF-7381 | Fixed the issue where the output was incorrect when converting PDF to Image. |
| Bug | SPIREPDF-7428 | Fixed the issue where black background images were generated when converting PDF to Image. |
| Bug | SPIREPDF-7498 | Fixed the issue where font size did not auto adjust when setting fonts and "Autosize" for PDF text fields. |
| Bug | SPIREPDF-7522 SPIREPDF-7537 |
Fixed the issue that it was failed to remove JavaScript from a PDF document. |
| Bug | SPIREPDF-6918 SPIREPDF-6919 |
Fixed the issue of incorrect rendering when converting PDF to images. |
| Bug | SPIREPDF-7117 | Fixed the inconsistency in transparency when converting PDF to images. |
Spire.XLS
| Category | ID | Description |
| New feature | SPIREXLS-5806 | Added support for the SHEETS function.
sheet.Range["B2"].Formula = "=SHEETS()"; sheet.Range["B3"].Formula = "=SHEETS(Sheet2!C5)"; sheet.Range["B4"].Formula = "=SHEETS(Sheet3:Sheet5!A1)"; sheet.Range["B6"].Formula = "=SHEETS(Sheet4!C5); |
| Bug | SPIREXLS-5802 | Fixed the issue where the AutoFitColumns effect was not working correctly. |
| Bug | SPIREXLS-5804 | Fixed the issue where the style of shapes was incorrect when copying worksheets. |
| Bug | SPIREXLS-5814 SPIREXLS-5853 |
Fixed the issue where the data was incorrect when saving a sheet as an image. |
| Bug | SPIREXLS-5819 | Fixed the issue where the saved Excel file reported errors when opened. |
| Bug | SPIREXLS-5832 | Fixed the issue where saving an Excel file to PDF/A3B was incorrect. |
| Bug | SPIREXLS-5834 | Fixed the issue where the left and right margins were incorrect when converting Excel to PDF. |
| Bug | SPIREXLS-5841 | Fixed the issue where the content was incorrect when converting a CellRange to an image. |
Spire.Prensentation
| Category | ID | Description |
| Bug | SPIREPPT-2876 | Fixed the issue where shapes were rendered incorrectly when converting slides to SVG. |
| Bug | SPIREPPT-2892 | Fixed the issue where images were cropped during PowerPoint-to-PDF conversion. |
Spire.DocViewer
| Category | ID | Description |
| Bug | SPIREDOCVIEWER-108 | Fixed the issue where documents displayed incompletely when zoom was set to 120%. |
| Bug | SPIREDOCVIEWER-115 | Optimized document rendering performance on the WPF platform. |
Como dividir um PDF em C# .NET: Um guia prático
Índice
Instalar com NuGet
PM> Install-Package Spire.PDF
Links Relacionados
No mundo do desenvolvimento de software e gerenciamento de documentos, saber como dividir PDF em C# é uma habilidade fundamental para desenvolvedores .NET. Quer você precise separar grandes relatórios em partes menores, extrair páginas específicas para distribuição ou organizar o conteúdo de forma mais eficiente, dividir arquivos PDF programaticamente pode economizar uma quantidade significativa de tempo e esforço.

Este guia explora como dividir arquivos PDF em C# usando a biblioteca Spire.PDF for .NET — uma solução de processamento de PDF robusta e livre de dependências.
- Apresentando o Spire.PDF for .NET
- Dividir um Documento PDF em C# - Exemplos de Código
- Dicas Avançadas para Divisão de PDF
- FAQs (demos em VB.NET)
- Conclusão
Apresentando o Spire.PDF for .NET
O Spire.PDF é uma biblioteca .NET rica em recursos que oferece:
- Capacidades abrangentes de manipulação de PDF
- Zero dependências do Adobe Acrobat
- Suporte para .NET Framework, .NET Core, .NET 5+, MonoAndroid e Xamarin.iOS
Antes de começar a dividir um PDF em vários arquivos em aplicações C#, é necessário instalar a biblioteca via Gerenciador de Pacotes NuGet.
- Abra seu projeto C# no Visual Studio.
- Clique com o botão direito no projeto no Gerenciador de Soluções e selecione "Gerenciar Pacotes NuGet".
- Na janela do Gerenciador de Pacotes NuGet, procure por "Spire.PDF".
- Selecione a versão apropriada da biblioteca e clique em "Instalar". O NuGet fará o download e adicionará as referências necessárias ao seu projeto.
Método Alternativo: Baixe manualmente a DLL do site oficial do Spire.PDF e referencie-a em seu projeto.
Dividir um Documento PDF em C# - Exemplos de Código
Agora que a biblioteca está configurada em seu projeto, vamos ver como dividir um PDF no .NET. Existem diferentes cenários para dividir um PDF, como dividi-lo em páginas individuais ou dividi-lo em vários PDFs com base em um número específico de páginas. Abordaremos ambos os casos comuns.
Dividir PDF em Páginas Individuais
A seguir, o exemplo de código C# para dividir um documento PDF em arquivos PDF individuais, cada um contendo uma única página do documento original:
using Spire.Pdf;
namespace SplitPDFIntoMultipleFiles
{
class Program
{
static void Main(string[] args)
{
// Especifique o caminho do arquivo de entrada
string inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";
// Especifique o diretório de saída
string outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";
// Crie um objeto PdfDocument
PdfDocument pdf = new PdfDocument();
// Carregue um arquivo PDF
pdf.LoadFromFile(inputFile);
// Divida o PDF em vários PDFs de uma página
pdf.Split(outputDirectory + "output-{0}.pdf", 1);
}
}
}
Ao chamar o método Split(), você pode dividir o documento PDF de entrada (contendo 10 páginas) em 10 arquivos individuais.

Dividir PDF em Vários Arquivos por Intervalos de Páginas
Suponha que você queira dividir um PDF grande em vários PDFs menores, cada um contendo um número especificado de páginas. Você pode criar dois ou mais novos documentos PDF e, em seguida, importar a página ou o intervalo de páginas do PDF de origem para eles.
Aqui estão os passos gerais para dividir um arquivo PDF por páginas em C#:
- Carregue o PDF de origem.
- Crie dois PDFs vazios para conter as páginas divididas.
- Dividir Páginas do PDF:
- Use o método InsertPage() para importar uma página específica do PDF de origem para o primeiro novo PDF.
- Use o método InsertPageRange() para importar um intervalo de páginas do PDF de origem para o segundo novo PDF.
- Salve ambos os novos PDFs no diretório de saída.
Exemplo de código C#:
using Spire.Pdf;
namespace SplitPdfByPageRanges
{
class Program
{
static void Main(string[] args)
{
// Especifique o caminho do arquivo de entrada
string inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";
// Especifique o diretório de saída
string outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";
// Carregue o arquivo PDF de origem ao inicializar o objeto PdfDocument
PdfDocument sourcePdf = new PdfDocument(inputFile);
// Crie dois novos documentos PDF
PdfDocument pdf1 = new PdfDocument();
PdfDocument pdf2 = new PdfDocument();
// Insira a primeira página do PDF de origem no primeiro documento
pdf1.InsertPage(sourcePdf, 0);
// Insira as páginas restantes do PDF de origem no segundo documento
pdf2.InsertPageRange(sourcePdf, 1, sourcePdf.Pages.Count - 1);
// Salve os dois documentos PDF
pdf1.SaveToFile(outputDirectory + "output-1.pdf");
pdf2.SaveToFile(outputDirectory + "output-2.pdf");
}
}
}
Ao executar este código, você pode extrair a página 1 e as páginas 2-10 do PDF de entrada em 2 arquivos PDF separados.

Dicas Avançadas para Divisão de PDF
-
Intervalos de Páginas Dinâmicos: Para dividir em vários intervalos (por exemplo, páginas 1-3, 5-7), crie objetos PdfDocument adicionais e ajuste o índice de inserção de página do método InsertPageRange().
-
Convenções de Nomenclatura de Arquivos: Use padrões descritivos ao nomear os arquivos de saída através do parâmetro destFilePattern do método Split() para organizar melhor os arquivos (por exemplo, report_part-{0}.pdf).
-
Tratamento de Erros: Adicione blocos try-catch para tratar exceções durante as operações de arquivo.
try
{
/* Código de divisão de PDF */
}
catch (Exception ex)
{
Console.WriteLine("Erro: " + ex.Message);
}
FAQs (demos em VB.NET)
Q1: Como removo marcas d'água no arquivo de saída?
R: Você pode solicitar uma licença de teste aqui (válida por 30 dias) para remover as marcas d'água e limitações. Ou você pode experimentar a edição gratuita da Comunidade.
Q2: A divisão preserva hiperlinks/campos de formulário?
R:
| Elementos | Preservado? |
| Hiperlinks | ✅ Sim |
| Campos de Formulário | ✅ Sim |
| Anotações | ✅ Sim |
| Assinaturas Digitais | ❌ Não (requer contexto completo do documento) |
Q3: Posso dividir uma única página de PDF em várias páginas/arquivos?
R: Sim. O Spire.PDF também suporta a divisão horizontal ou vertical de uma página de PDF em duas ou mais páginas. Tutorial: Dividir uma Página de PDF em Várias Páginas em C#
Q4: Existe uma demonstração em VB.NET для dividir arquivos PDF?
R: Como uma biblioteca .NET nativa, o Spire.PDF funciona de forma idêntica em C# e VB.NET. Portanto, você pode usar alguma ferramenta de conversão de código (por exemplo, Telerik Code Converter) para traduzir instantaneamente os exemplos de C# para VB.NET.
Conclusão
O Spire.PDF simplifica a divisão de PDFs em C# com métodos intuitivos. Se você precisa de uma divisão básica página por página ou de uma divisão mais avançada baseada em intervalos de páginas, a biblioteca fornece a funcionalidade necessária. Seguindo este guia, você pode implementar eficientemente a divisão de PDF em suas aplicações C# ou VB.NET, melhorando a produtividade e o gerenciamento de documentos.
Onde Obter Ajuda
Dica Profissional: Combine a divisão com os recursos de conversão do Spire.PDF para extrair páginas como imagens ou outros formatos de arquivo.
Как разделить PDF в C# .NET: Практическое руководство
Оглавление
Установка через NuGet
PM> Install-Package Spire.PDF
Похожие ссылки
В мире разработки программного обеспечения и управления документами знание того, как разделить PDF на C#, является фундаментальным навыком для разработчиков .NET. Независимо от того, нужно ли вам разделять большие отчеты на более мелкие части, извлекать определенные страницы для распространения или более эффективно организовывать контент, программное разделение файлов PDF может сэкономить значительное количество времени и усилий.

В этом руководстве рассматривается, как разделять файлы PDF на C# с помощью библиотеки Spire.PDF for .NET — надежного решения для обработки PDF без зависимостей.
- Представляем Spire.PDF for .NET
- Разделение документа PDF на C# - Примеры кода
- Расширенные советы по разделению PDF
- Часто задаваемые вопросы (демо на VB.NET)
- Заключение
Представляем Spire.PDF for .NET
Spire.PDF — это многофункциональная библиотека .NET, предлагающая:
- Комплексные возможности для работы с PDF
- Нулевая зависимость от Adobe Acrobat
- Поддержка .NET Framework, .NET Core, .NET 5+, MonoAndroid и Xamarin.iOS
Прежде чем вы сможете начать разделение PDF на несколько файлов в приложениях C#, необходимо установить библиотеку через менеджер пакетов NuGet.
- Откройте свой проект C# в Visual Studio.
- Щелкните правой кнопкой мыши по проекту в обозревателе решений и выберите «Управление пакетами NuGet».
- В окне менеджера пакетов NuGet найдите «Spire.PDF».
- Выберите подходящую версию библиотеки и нажмите «Установить». NuGet загрузит и добавит необходимые ссылки в ваш проект.
Альтернативный метод: вручную загрузите DLL с официального сайта Spire.PDF и сошлитесь на нее в своем проекте.
Разделение документа PDF на C# - Примеры кода
Теперь, когда библиотека настроена в вашем проекте, давайте посмотрим, как разделить PDF в .NET. Существуют различные сценарии разделения PDF, такие как разделение на отдельные страницы или на несколько PDF-файлов на основе определенного количества страниц. Мы рассмотрим оба распространенных случая.
Разделить PDF на отдельные страницы
Ниже приведен пример кода на C# для разделения документа PDF на отдельные PDF-файлы, каждый из которых содержит одну страницу из исходного документа:
using Spire.Pdf;
namespace SplitPDFIntoMultipleFiles
{
class Program
{
static void Main(string[] args)
{
// Укажите путь к входному файлу
string inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";
// Укажите выходной каталог
string outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";
// Создайте объект PdfDocument
PdfDocument pdf = new PdfDocument();
// Загрузите PDF-файл
pdf.LoadFromFile(inputFile);
// Разделите PDF на несколько одностраничных PDF-файлов
pdf.Split(outputDirectory + "output-{0}.pdf", 1);
}
}
}
Вызвав метод Split(), вы можете разделить входной PDF-документ (содержащий 10 страниц) на 10 отдельных файлов.

Разделить PDF на несколько файлов по диапазонам страниц
Предположим, вы хотите разделить большой PDF-файл на несколько меньших PDF-файлов, каждый из которых содержит указанное количество страниц. Вы можете создать два или более новых документа PDF, а затем импортировать в них страницу или диапазон страниц из исходного PDF.
Вот общие шаги по разделению файла PDF по страницам на C#:
- Загрузите исходный PDF.
- Создайте два пустых PDF-файла для хранения разделенных страниц.
- Разделите страницы PDF:
- Используйте метод InsertPage() для импорта указанной страницы из исходного PDF в первый новый PDF.
- Используйте метод InsertPageRange() для импорта диапазона страниц из исходного PDF во второй новый PDF.
- Сохраните оба новых PDF-файла в выходной каталог.
Пример кода на C#:
using Spire.Pdf;
namespace SplitPdfByPageRanges
{
class Program
{
static void Main(string[] args)
{
// Укажите путь к входному файлу
string inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";
// Укажите выходной каталог
string outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";
// Загрузите исходный PDF-файл при инициализации объекта PdfDocument
PdfDocument sourcePdf = new PdfDocument(inputFile);
// Создайте два новых документа PDF
PdfDocument pdf1 = new PdfDocument();
PdfDocument pdf2 = new PdfDocument();
// Вставьте первую страницу исходного PDF в первый документ
pdf1.InsertPage(sourcePdf, 0);
// Вставьте остальные страницы исходного PDF во второй документ
pdf2.InsertPageRange(sourcePdf, 1, sourcePdf.Pages.Count - 1);
// Сохраните два документа PDF
pdf1.SaveToFile(outputDirectory + "output-1.pdf");
pdf2.SaveToFile(outputDirectory + "output-2.pdf");
}
}
}
Выполнив этот код, вы можете извлечь страницу 1 и страницы 2-10 из входного PDF в 2 отдельных PDF-файла.

Расширенные советы по разделению PDF
-
Динамические диапазоны страниц: чтобы разделить на несколько диапазонов (например, страницы 1-3, 5-7), создайте дополнительные объекты PdfDocument и настройте индекс вставки страниц метода InsertPageRange().
-
Соглашения об именовании файлов: используйте описательные шаблоны при именовании выходных файлов через параметр destFilePattern метода Split() для лучшей организации файлов (например, report_part-{0}.pdf).
-
Обработка ошибок: добавьте блоки try-catch для обработки исключений во время файловых операций.
try
{
/* Код для разделения PDF */
}
catch (Exception ex)
{
Console.WriteLine("Ошибка: " + ex.Message);
}
Часто задаваемые вопросы (демо на VB.NET)
В1: Как удалить водяные знаки в выходном файле?
О: Вы можете запросить пробную лицензию здесь (действительна в течение 30 дней), чтобы удалить водяные знаки и ограничения. Или вы можете попробовать бесплатную версию Community.
В2: Сохраняются ли при разделении гиперссылки/поля форм?
О:
| Элементы | Сохранено? |
| Гиперссылки | ✅ Да |
| Поля форм | ✅ Да |
| Аннотации | ✅ Да |
| Цифровые подписи | ❌ Нет (требуется полный контекст документа) |
В3: Могу ли я разделить одну страницу PDF на несколько страниц/файлов?
О: Да. Spire.PDF также поддерживает горизонтальное или вертикальное разделение страницы PDF на две или более страниц. Руководство: Разделение страницы PDF на несколько страниц на C#
В4: Есть ли демо-версия на VB.NET для разделения PDF-файлов?
О: Будучи нативной библиотекой .NET, Spire.PDF работает одинаково как на C#, так и на VB.NET. Поэтому вы можете использовать какой-либо инструмент для конвертации кода (например, Telerik Code Converter) для мгновенного перевода примеров с C# на VB.NET.
Заключение
Spire.PDF упрощает разделение PDF-файлов на C# с помощью интуитивно понятных методов. Независимо от того, нужно ли вам базовое разделение по страницам или более сложное разделение на основе диапазонов страниц, библиотека предоставляет необходимую функциональность. Следуя этому руководству, вы сможете эффективно реализовать разделение PDF в своих приложениях на C# или VB.NET, повысив производительность и управление документами.
Где получить помощь
Совет профессионала: комбинируйте разделение с функциями преобразования Spire.PDF для извлечения страниц в виде изображений или других форматов файлов.