Java csv to pdf

Convert CSV to PDF in Java

CSV to PDF conversion with a few lines of Java code

GroupDocs.Conversion

About GroupDocs.Conversion for Java API

GroupDocs.Conversion for Java is an advanced file format conversion API for converting between popular image and document formats such as Microsoft Office, OpenDocument, PDF, HTML, email, CAD. and much more with just a few lines of code. The native API automatically detects the formats of the original documents and offers many options for customizing the converted documents. Along with the function of extracting information from a document, it also supports caching of the conversion results to the local disk by default. However, any type of cache storage can be supported by implementing the appropriate interfaces — Amazon S3, Dropbox, Google Drive, Windows Azure, Reddis, or any others.

Читайте также:  Html теги параметры тегов

Convert your CSV files to PDF in Java. It only takes a couple of lines of Java code on any platform of your choice, such as Windows, Linux, macOS. You can try converting CSV to PDF for free and evaluate the quality of the conversion results. Along with simple file conversion scripts, you can try more sophisticated options for loading the CSV source file and storing the PDF output.

For example, for the source CSV file you may use the following load options:

  • automatic detection of the file format;
  • specify a password for protected files (if the file format supports it);
  • replace missing fonts to preserve the appearance of the document.

There are also advanced convert options for the PDF file:

  • convert a specific page of a document or a range of pages;
  • add a watermark to the converted PDF.

Once the conversion is complete, you can save the PDF file to your local file path or to any third party storage such as FTP, Amazon S3, Google Drive, Dropbox etc. Please note — to convert CSV to PDF, you do not need to install any additional software, such as MS Office, Open Office, Adobe Acrobat Reader etc.

Steps to convert CSV to PDF in Java

GroupDocs.Conversion for Java allows developers to easily convert CSV file to PDF with a few lines of code.

  • Create a new instance of the Converter class and upload the file CSV with the full path
  • Set ConvertOptions for document type to PDF
  • Call the convert() method and pass the document name (full path) and format (PDF) as a parameter
Читайте также:  Request session python get

System Requirements

Basic conversion with GroupDocs.Conversion for Java API can be done with just a few lines of code. Our APIs are supported on all major platforms and operating systems. Before executing the code below, make sure you have the following prerequisites installed on your system.

  • Operating systems: Microsoft Windows, Linux, MacOS
  • Development environments: NetBeans, Intellij IDEA, Eclipse, etc.
  • Java runtime: J2SE 6.0 and above
  • Get the latest GroupDocs.Conversion for Java from Maven
// Load source file CSV for conversion  Converter converter = new Converter("input.csv");  // Prepare conversion options for target format PDF  ConvertOptions convertOptions = new FileType().fromExtension("pdf").getConvertOptions();  // Convert to PDF format  converter.convert("output.pdf", convertOptions); 

CSV to PDF Live Demo

Visit our GroupDocs.Conversion App website and try CSV to PDF conversion now. The free demo has the following benefits

No need to write any code

Just upload the source file

Get download link to save the file

Other supported CSV conversions in Java

You can also convert CSV to many other file formats. Please see the list below.

(OpenDocument Flat XML Spreadsheet)

(Hypertext Markup Language File)

(Hyper Text Markup Language)

(JavaScript Object Notation File)

(StarOffice Calc Spreadsheet)

(Microsoft Excel Spreadsheet (Legacy))

(Excel Macro-Enabled Template)

Источник

Convert CSV to PDF– Java Program Example

In this series, we are providing examples for converting a CSV file to PDF using Java. In this part of the series, we will provide a standalone program in Java that will do the following:

  • Read input CSV file
  • Create PDF document
  • Populate a PDF table from the contents of the CSV file
  • Writes PDF file to output

Each of these steps is described briefly now. The full Java program is provided at the end of this post.

Read Input CSV File

In this step, we will use opencsv-2.3.jar file, and read the input CSV file data into the program memory. The program assumes the CSV file has two columns, even though you can make that dynamic depending on your needs. A code fragment that reads a CSV file is given below:

 /* Step -1 : Read input CSV file in Java */ String inputCSVFile = "csv_to_pdf.csv"; CSVReader reader = new CSVReader(new FileReader(inputCSVFile));

Create PDF document

We will use itextpdf-5.3.4.jar and create a Document object, and attach it to a PdfWriter object at this step. This will create a PDF file for us and we can start writing the contents of the CSV file to the PDF following this. We will also create iText table objects that maps to a physical PDF table and will hold CSV file data. The code fragment is provided below:

 /* Step-2: Initialize PDF documents - logical objects */ Document my_pdf_data = new Document(); PdfWriter.getInstance(my_pdf_data, new FileOutputStream("converted_PDF_File.pdf")); my_pdf_data.open(); PdfPTable my_first_table = new PdfPTable(2); PdfPCell table_cell;

Populate PDF table from CSV data

In this step, we will loop through the CSV file line by line and dump the contents of this file into a PDF table. We will use Pdfptable object to capture CSV file data and attach this table to the PDF document created earlier.

 /* Step -3: Loop through CSV file and populate data to PDF table */ while ((nextLine = reader.readNext()) != null)  lnNum++; table_cell=new PdfPCell(new Phrase(nextLine[0])); my_first_table.addCell(table_cell); table_cell=new PdfPCell(new Phrase(nextLine[1])); my_first_table.addCell(table_cell); >

Write PDF file to output

Once all the lines in the CSV file are read, we close the PDF document and the write the output to a file. The CSV file opened for reading can also be closed at this point. We also attach the logical PDF table to Document object at this step. This ensures the table is written to PDF.

 /* Step -4: Attach table to PDF and close the document */ my_pdf_data.add(my_first_table); my_pdf_data.close(); 

CSV to PDF – Complete Java Program

The complete Java program that converts a CSV file to a table in PDF document is provided below:

import java.io.FileOutputStream; import java.io.*; import au.com.bytecode.opencsv.CSVReader; import java.io.FileReader; import java.util.*; import com.itextpdf.text.*; import com.itextpdf.text.pdf.*; public class csv2pdf  public static void main(String[] args) throws Exception /* Step -1 : Read input CSV file in Java */ String inputCSVFile = "csv_to_pdf.csv"; CSVReader reader = new CSVReader(new FileReader(inputCSVFile)); /* Variables to loop through the CSV File */ String [] nextLine; /* for every line in the file */ int lnNum = 0; /* line number */ /* Step-2: Initialize PDF documents - logical objects */ Document my_pdf_data = new Document(); PdfWriter.getInstance(my_pdf_data, new FileOutputStream("converted_PDF_File.pdf")); my_pdf_data.open(); PdfPTable my_first_table = new PdfPTable(2); PdfPCell table_cell; /* Step -3: Loop through CSV file and populate data to PDF table */ while ((nextLine = reader.readNext()) != null)  lnNum++; table_cell=new PdfPCell(new Phrase(nextLine[0])); my_first_table.addCell(table_cell); table_cell=new PdfPCell(new Phrase(nextLine[1])); my_first_table.addCell(table_cell); > /* Step -4: Attach table to PDF and close the document */ my_pdf_data.add(my_first_table); my_pdf_data.close(); > >

CSV to PDF – Output Snapshot

CSV to PDF Conversion in Java - Example Output
CSV to PDF — Java Program Output — Example

That completes the standalone Java program example for the tutorial. In the next part, we will examine how to create a servlet for this conversion. Related links to this series are available below:

Источник

Generate Reports from CSV Data in Java

The Comma Separated Values (CSV) is a file format for storing the data in the form of plain text where the values are separated by commas. CSV is widely used for exchanging data among applications. As a developer, we often need to convert the large CSV data into a presentable format. This article will guide you to convert CSV data into PDF and MS Word reports in Java using a simple template.

The following topics are covered below:

Report Generation Java API#

GroupDocs.Assembly for Java is the report generation API that I have used in this article to generate reports from the selected CSV data and a template in TXT format. It also supports report generation automation from multiple data sources like JSON, XML, and also from MS Word, Excel, and PowerPoint files as data files.

Download or Configure#

You may download the JAR file from the downloads section, or just get the repository and dependency configurations for the pom.xml of your maven-based Java applications.

 GroupDocsJavaAPI GroupDocs Java API http://repository.groupdocs.com/repo/  com.groupdocs groupdocs-assembly 21.4  

Generate PDF Report from CSV Data in Java#

Let’s start with the transformation of data into presentable PDF. The following steps will lead you to convert CSV data into a formatted PDF report.

CSV to PDF Report in Java

  • Load CSV data source
  • Define template according to the CSV data
  • Provide CSV data source and template to simple method to generate PDF report.

CSV Data#

For the PDF report generation, I will be using the following sample CSV data of different persons along with their respective ages and date of birth.

Name,Age,Birth John Doe,32,4/1/1989 16:00 Jane Doe,29,1/31/1992 7:00 John Smith,53,3/8/1968 13:00 

Template#

Define the following template in TXT or DOCX format. This allows iterating the list of persons with their details. After that, you can jump to the code for report generation.

>Name: >, Age: >, Date of Birth: > > Average age: <<\[persons.**average**(p =>p.Age)\]>> 

Java Steps to Generate PDF Report from CSV#

The following steps explain the automatic conversion of CSV data into a PDF report according to the defined template.

  • Define CSV data file, .txt template file, and PDF output report file paths.
  • Instantiate CsvDataSoure with CSV data file.
  • Create DataSourceInfo with the defined CsvDataSource.
  • Call the assembleDocument method of the DocumentAssembler class to get the generated PDF report.

The following code shows how to convert CSV data to PDF report in Java.

Generate MS Word Report from CSV data in Java#

It is very similar to the above PDF report generation, you can easily create the MS Word DOC/DOCX report from the CSV data:

  • Load the CSV data from file.
  • Defining the template in TXT or DOCX format.
  • Set the output report document format as DOC/DOCX.
  • The rest of the code will remain the same to generate MS Word DOCX report from the CSV data.

The following code shows how to convert CSV data to DOCX report in Java.

Get a Free API License#

You can get a free temporary license in order to use the API without the evaluation limitations.

Conclusion#

To sum up, you have learned to convert the CSV data into PDF and MS Word reports in Java. I hope you are now comfortable building your own Java-based application to generate reports by converting CSV data to PDF format. Similarly, you can generate reports using data sources like JSON and XML.

For more about the API, you can visit documentation and the GitHub repository. In case of further queries and ambiguities, contact the free support on the forum.

See Also#

Источник

Convert CSV to PDF in Java

A CSV file is a plain text file containing only numbers and letters. Due to its wide compatibility, this file format is often used to transfer tabular data between programs and databases. This article will share how to programmatically convert a CSV file to PDF using a free Java API.

Import Dependency (2 Methods)

1# Download the free API (Free Spire.XLS for Java) and unzip it, then add the Spire.Xls.jar file to your project as dependency. 2# Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.

   com.e-iceblue e-iceblue https://repo.e iceblue.com/nexus/content/groups/public/     e-iceblue spire.xls.free 5.1.0   

Sample Code

It’s quite simple to convert a CSV file to PDF using the free API, and the complete sample code is shown as below.

import com.spire.xls.Workbook; import com.spire.xls.Worksheet; public class ConvertCsvToPdf  public static void main(String []args)  //Create a Workbook instance Workbook wb = new Workbook(); //Load a CSV file wb.loadFromFile("input.csv", ","); //Set SheetFitToPage property as true to ensure the worksheet is converted to 1 PDF page wb.getConverterSetting().setSheetFitToPage(true); //Get the first worksheet Worksheet sheet = wb.getWorksheets().get(0); //Loop through the columns in the worksheet for (int i = 1; i  sheet.getColumns().length; i++)  //AutoFit columns sheet.autoFitColumn(i); > //Save the worksheet to PDF sheet.saveToPdf("toPDF.pdf"); > > 

Источник

Оцените статью