I'm new to java, and I'm learning how to create PDF, I was using Itext to create PDF, but because it handles a license I stopped using it, and started using PDFbox. I've searched the internet for how to convert from CSV to PDF, but I can't find an example of how to use margins, or how to align the content.
Using Itext, this is my code using Itext7, it works perfectly but i want to migrate it to PDFbox
public static boolean isEmpty(File rutaCSV) {
if(rutaCSV.isDirectory()){
String[] csvFiles = rutaCSV.list();
if (csvFiles.length > 0) {
for (String cadena : csvFiles){
readCSV("path");
try{
File csvFile = new File("path");
if (csvFile.exists()){
csvFile.delete();
return false;
}
System.out.println(csvFile.delete());
}catch(Exception ex){
System.out.println(ex);
}
}
return true;
}else{
System.out.println("There's not files");
return true;
}
}
return true;
}
public static void readCSV(String file, String cadena){
try{
FileReader filereader = new FileReader(file);
// Configuración para leer el archivo con ;
CSVParser parser = new CSVParserBuilder().withSeparator(';').build();
CSVReader csvReader = new CSVReaderBuilder(filereader)
.withCSVParser(parser)
.build();
Document pdfDocument = new Document();
pdfDocument.addTitle("Some");
pdfDocument.setMargins(0, 0,25,25);
String fileName = cadena.replaceFirst("[.][^.]+$", "");
PdfWriter.getInstance(pdfDocument, new FileOutputStream("path"+fileName+".pdf"));
pdfDocument.open();
PdfPTable tableData = new PdfPTable(5);
PdfPCell cells;
// Lista para guardar los datos leídos
List<String[]> allData = csvReader.readAll();
for (String[] row : allData) {
for (String cell : row) {
cells =new PdfPCell(new Phrase(cell));
tableData.addCell(cells);
}
}
pdfDocument.addTitle("Some");
pdfDocument.add(tableData);
pdfDocument.close();
}catch(Exception ex){
ex.printStackTrace();
System.out.println("error");
}
}
Using PDFBox
public static void main(String[] args) throws IOException, CsvException {
PDDocument document = new PDDocument();
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
PDPageContentStream content = new PDPageContentStream(document, page);
try{
String file = "C:\\Users\\brayan.milian\\Desktop\\pruebaFTP\\prueba.csv";
FileReader filereader = new FileReader(file);
CSVParser parser = new CSVParserBuilder().withSeparator(';').build();
CSVReader csvReader = new CSVReaderBuilder(filereader)
.withCSVParser(parser)
.build();
List<String[]> allData = csvReader.readAll();
for (String row[] : allData) {
for (String cell : row){
content.beginText();
content.setFont(PDType1Font.TIMES_BOLD, 12);
content.showText(cell);
content.endText();
}
}
content.close();
}catch(Exception ex){
System.out.println("dja");
}
Can anyone help me?
Related
My issue is that I am using ByteArrayOutputStream class to display excel file with data and retrieved using toByteArray()
Issue: After I download the Excel file, the cells stops displaying required color after certain cells and I am unable to understand where it went wrong.
Code being used:
protected ByteArrayOutputStream createXLS(Map contextMap) throws FwkException {
long compteurLigne = 0;
// On cree un classeur
HSSFWorkbook wb = new HSSFWorkbook();
// Pour chaque poste, on cree une feuille
// On cree une feuille
HSSFSheet s = wb.createSheet();
// Creation entete de la feuille
creerEntete(wb, s, contextMap);
setTableHead(wb, s, contextMap);
List listePoste = (List) contextMap.get("list");
for (Iterator ite = listePoste.iterator(); ite.hasNext();) {
HypothesesCompararerOutillagePoste hypothesesCompararerOutillagePoste = (HypothesesCompararerOutillagePoste) ite.next();
creerLigneMatrice(hypothesesCompararerOutillagePoste, s, wb);
setTailleColonne(s);
}
ByteArrayOutputStream dataOut = new ByteArrayOutputStream();
try {
wb.write(dataOut);
} catch (IOException e) {
throw new TechnicalException("Error while writing the output to de workbook", e);
}
return dataOut;
}
Main Logic for colour being displayed in Excel file(xls):
private void setCsPplusOuMoinsOutillageColor(HSSFCellStyle csPplusOuMoinsOutillage, String plusOuMoinsOutillage) {
if (plusOuMoinsOutillage != null) {
if (plusOuMoinsOutillage.equals("-")) {
csPplusOuMoinsOutillage.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
csPplusOuMoinsOutillage.setFillForegroundColor(HSSFColor.RED.index);
} else if (plusOuMoinsOutillage.equals("+")) {
csPplusOuMoinsOutillage.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
csPplusOuMoinsOutillage.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);
} else {
csPplusOuMoinsOutillage.setFillPattern(HSSFCellStyle.NO_FILL);
}
}
}
Below is the code where data gets retrieved toByteArray():
protected void doEoxExecute() throws FwkException {
try {
Map contextMap = (Map) getInput(IN_CONTEXT_MAP);
String langue = (String) getInput(IN_LOCALE_LANGUAGE);
String pays = (String) getInput(IN_LOCALE_COUNTRY);
Collection<Object> listeMsg = (Collection) getInput(IN_LOGGER_MSG);
if (listeMsg != null && !listeMsg.isEmpty()) {
Iterator<Object> iter = listeMsg.iterator();
while (iter.hasNext()) {
Object msg = iter.next();
if (msg instanceof String)
batchlog.info((String) msg);
}
}
locale = null;
if (langue != null) {
if (pays != null)
locale = new Locale(langue, pays);
else
locale = new Locale(langue);
} else
locale = Locale.FRANCE;
boolean inSec = Boolean.parseBoolean((String) getInput(IN_TIME_IN_SEC));
EOXContext.setCtx(!inSec, locale);
ByteArrayOutputStream out = createXLS(contextMap);
byte[] xls = out.toByteArray();
// si aucune donnee, on affiche un message a l'utilisateur
if (xls == null) {
batchlog.info(getMessage(broker, "commun.export.xls.aucuneDonnee", locale));
} else {
String repertoireTemporaire = EoxBatchService.getPropriete(FICHIER_PROPERTIES, "GenererXlsDocPoste.io.temp", null);
if (repertoireTemporaire == null)
repertoireTemporaire = EoxBatchService.getPropriete(EoxConstants.FICHIER_PROPRIETES_SERVEUR, "GenererXlsDocPoste.io.temp", null);
if (repertoireTemporaire != null) {
File repertoire = new File(repertoireTemporaire);
File fichierXls = File.createTempFile("doc", ".xls", repertoire);
if (logger.isInfoEnabled())
logger.info("creation fichier XLS : " + fichierXls.getAbsolutePath());
FileOutputStream fos = new FileOutputStream(fichierXls);
fos.write(xls);
fos.flush();
fos.close();
Also I am attaching the output of the excel file which shows no colors after certain 35th cell:
The CSV look like this:
Name;Amount;Date
Netflix;5;1.1.2021
I want a different list for each expense, one for entertainment one for transport etc. However, I only want the amount to be stored on a list, how would I do that?
public class CsvReader {
public static void readDataLineByLine(String file) {
try {
// Create an object of file reader class with CSV file as a parameter.
FileReader filereader = new FileReader(file);
// create csvParser object with
// custom separator semi-colon
CSVParser parser = new CSVParserBuilder().withSeparator(';').build();
// create csvReader object with parameter
// filereader and parser
CSVReader csvReader = new CSVReaderBuilder(filereader).withCSVParser(parser).build();
// Read all data at once
List<String[]> allData = csvReader.readAll();
List<String> entertainment = new ArrayList<>();
// Print Data.
for (String[] row : allData) {
for (String cell : row) {
System.out.print(cell + "\t");
if (cell.startsWith("Netflix")){
entertainment.add(cell);
}
}
System.out.println();
System.out.println(entertainment);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
CsvReader.readDataLineByLine("tt.csv");
}
}
If you use opencsv , how about writing the code like below? Please review.
public class CsvReader {
public static void readDataLineByLine(String file) {
try {
// Create an object of file reader class with CSV file as a parameter.
FileReader filereader = new FileReader(file);
// create csvParser object with
// custom separator semi-colon
CSVParser parser = new CSVParserBuilder().withSeparator(';').build();
// create csvReader object with parameter
// filereader and parser
CSVReader csvReader = new CSVReaderBuilder(filereader).withCSVParser(parser).build();
List<String> entertainment = new ArrayList<>();
// changed part
int index = 0;
while ((nextLine = reader.readNext()) != null) { // 2
// csv header exclusion condition
if(index == 0) {
continue;
}
String name = nextLine[0];
String amount = nextLine[1];
if (name.startsWith("Netflix")){
entertainment.add(amount);
}
index++;
}
// Print Data.
System.out.println();
System.out.println(entertainment);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
CsvReader.readDataLineByLine("tt.csv");
}
}
I have implemented Apache POI library for Page count of Doc pages, but it shows page count zero when I download Google Doc as .docx file.
Edit: My code is as follows
public Integer getPagesCount(byte[] docBytes, String type)
throws IOException {
ByteArrayInputStream in = new ByteArrayInputStream(docBytes);
String lowerFilePath = type.toLowerCase();
if (lowerFilePath.equals("docx")) {
#SuppressWarnings("resource")
XWPFDocument docx = new XWPFDocument(in);
return docx.getProperties().getExtendedProperties()
.getUnderlyingProperties().getPages();
} else if (lowerFilePath.equals("doc")) {
#SuppressWarnings("resource")
HWPFDocument wordDoc = new HWPFDocument(in);
return wordDoc.getSummaryInformation().getPageCount();
} else if (lowerFilePath.equals("ppt")) {
HSLFSlideShow document = new HSLFSlideShow(in);
return document.getSlides().size();
} else if (lowerFilePath.equals("pptx")) {
#SuppressWarnings("resource")
XMLSlideShow xslideShow = new XMLSlideShow(in);
return xslideShow.getSlides().size();
} else if (lowerFilePath.equals("pdf")) {
PDDocument doc = PDDocument.load(in);
return doc.getNumberOfPages();
}
return 0;
}
I am currently trying to create an application that converts any font code from a software project into a PDF. I'm using iText to generate the PDF but I can't keep the tabbing of the file.
Here's the method that reads the files(simple bufferedReader, but I get every read line and put it in a linkedList):
public static LinkedList<String> lerArquivoQualquerDeTexto(String URL) {
LinkedList<String> textoLido = new LinkedList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(URL)))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null)
{
System.out.println(sCurrentLine);
textoLido.add(sCurrentLine + System.lineSeparator());
}
return textoLido;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
And here's the iText convertion of this LinkedList i just read using BufferedReader:
private static String FILE = "c:/temp/FirstPdf.pdf";
private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
Font.BOLD);
private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 9,
Font.NORMAL, BaseColor.RED);
private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,
Font.BOLD);
private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.BOLD);
private static Font smallFont = new Font(Font.FontFamily.TIMES_ROMAN, 9,
Font.NORMAL);
/**
* gera o PDF de UM único arquivo já lido
* #param textoLido texto lido pelo buffer
* #param nomeDoArquivoLido nome do arquivo lido, já obtido pelo LeitorArquivoTexto.java
* #return
*/
public static boolean gerarPDFDeString(LinkedList<String> textoLido, String nomeDoArquivoLido)
{
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
addMetaData(document);
addTitlePage(document);
addContent(document, textoLido, nomeDoArquivoLido);
document.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
// iText allows to add metadata to the PDF which can be viewed in your Adobe
// Reader
// under File -> Properties
private static void addMetaData(Document document) {
document.addTitle("My first project to register");
document.addSubject("Using iText");
document.addKeywords("Java, PDF, iText");
document.addAuthor("Lars Vogel");
document.addCreator("Lars Vogel");
}
private static void addTitlePage(Document document)
throws DocumentException {
Paragraph preface = new Paragraph();
// We add one empty line
addEmptyLine(preface, 1);
// Lets write a big header
preface.add(new Paragraph("Nome Do Projeto", redFont));
addEmptyLine(preface, 1);
// Will create: Report generated by: _name, _date
preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
smallBold));
addEmptyLine(preface, 3);
document.add(preface);
// Start a new page
document.newPage();
}
private static void addContent(Document document, LinkedList<String> textoArquivoLido, String nomeDoArquivoLido) throws DocumentException {
Anchor anchor = new Anchor(nomeDoArquivoLido, redFont);
anchor.setName(nomeDoArquivoLido);
// Second parameter is the number of the chapter
Chapter catPart = new Chapter(new Paragraph(anchor), 1);
for(int i = 0; i < textoArquivoLido.size(); i++)
{
String umaLinhaLida = textoArquivoLido.get(i);
Phrase umaLinhaDoPdf = new Phrase(umaLinhaLida, smallFont);
catPart.add(umaLinhaDoPdf);
}
// now add all this to the document
document.add(catPart);
}
I'm trying to convert a .java file from my java project, but the problem is: my output file(the .pdf file) keeps being written without any of my formatting tabs! Any ideas how to solve this?
I'm trying to convert RTF to HTML using Libre. Its working fine for Libre Document but giving null value for Spreadsheet. Below is my java code how I do the parse.
ArrayList<String> styleValue = new ArrayList<String>();
String result;
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clipboard.getContents(null);
DataFlavor dfRTF = new DataFlavor("text/rtf", "Rich Formatted Text");
DataFlavor dfTxt = DataFlavor.stringFlavor;
result = rtfToHtml(new StringReader(streamToString((InputStream) contents.getTransferData(dfRTF))));
rtfToHtml ()
public static String rtfToHtml(Reader rtf) throws IOException {
JEditorPane p = new JEditorPane();
p.setContentType("text/rtf");
EditorKit kitRtf = p.getEditorKitForContentType("text/rtf");
try {
kitRtf.read(rtf, p.getDocument(), 0);
kitRtf = null;
EditorKit kitHtml = p.getEditorKitForContentType("text/html");
Writer writer = new StringWriter();
kitHtml.write(writer, p.getDocument(), 0, p.getDocument().getLength());
return writer.toString();
} catch (BadLocationException e) {
e.printStackTrace();
}
return null;
}
Appreciated if anyone could help me to fix this for Libre spreadsheet. Please advice.