Skip to content

Commit

Permalink
error handling, excel, bug fixes, name fixes (#57)
Browse files Browse the repository at this point in the history
  • Loading branch information
Frooodle authored Feb 24, 2023
1 parent 6135d08 commit 67345d0
Show file tree
Hide file tree
Showing 27 changed files with 558 additions and 45 deletions.
6 changes: 6 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ dependencies {
implementation 'org.apache.pdfbox:pdfbox:2.0.27'
implementation 'org.apache.logging.log4j:log4j-core:2.19.0'
implementation 'e-iceblue:spire.pdf.free:5.1.0'

implementation 'org.apache.poi:poi:5.2.0'
implementation 'org.apache.poi:poi-ooxml:5.2.0'
implementation 'com.itextpdf:itextpdf:5.5.13.2'


}

jar {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import com.spire.pdf.exporting.PdfImageInfo;
import com.spire.pdf.graphics.PdfBitmap;

import stirling.software.SPDF.utils.ErrorUtils;
import stirling.software.SPDF.utils.PdfUtils;

//import com.spire.pdf.*;
Expand All @@ -35,7 +36,6 @@ public String compressPdfForm(Model model) {
@PostMapping("/compress-pdf")
public ResponseEntity<byte[]> compressPDF(@RequestParam("fileInput") MultipartFile pdfFile, @RequestParam("imageCompressionLevel") String imageCompressionLevel)
throws IOException {

// Load a sample PDF document
PdfDocument document = new PdfDocument();
document.loadFromBytes(pdfFile.getBytes());
Expand All @@ -61,7 +61,7 @@ public ResponseEntity<byte[]> compressPDF(@RequestParam("fileInput") MultipartFi
}
}

return PdfUtils.pdfDocToWebResponse(document, pdfFile.getName() + "_compressed.pdf");
return PdfUtils.pdfDocToWebResponse(document, pdfFile.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_compressed.pdf");

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public ResponseEntity<byte[]> overlayImage(@RequestParam("fileInput") MultipartF
byte[] imageBytes = imageFile.getBytes();
byte[] result = PdfUtils.overlayImage(pdfBytes, imageBytes, x, y);

return PdfUtils.bytesToWebResponse(result, pdfFile.getName() + "_overlayed.pdf");
return PdfUtils.bytesToWebResponse(result, pdfFile.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_overlayed.pdf");
} catch (IOException e) {
logger.error("Failed to add image to PDF", e);
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public ResponseEntity<byte[]> deletePages(@RequestParam("fileInput") MultipartFi
document.removePage(pageIndex);
}

return PdfUtils.pdfDocToWebResponse(document, pdfFile.getName() + "_removed_pages.pdf");
return PdfUtils.pdfDocToWebResponse(document, pdfFile.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_removed_pages.pdf");

}

Expand Down Expand Up @@ -111,7 +111,7 @@ public ResponseEntity<byte[]> rearrangePages(@RequestParam("fileInput") Multipar
document.addPage(page);
}

return PdfUtils.pdfDocToWebResponse(document, pdfFile.getName() + "_rearranged.pdf");
return PdfUtils.pdfDocToWebResponse(document, pdfFile.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_rearranged.pdf");
} catch (IOException e) {

logger.error("Failed rearranging documents", e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public ResponseEntity<byte[]> rotatePDF(@RequestParam("fileInput") MultipartFile
page.setRotation(page.getRotation() + angle);
}

return PdfUtils.pdfDocToWebResponse(document, pdfFile.getName() + "_rotated.pdf");
return PdfUtils.pdfDocToWebResponse(document, pdfFile.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_rotated.pdf");

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public ResponseEntity<byte[]> convertToPdf(@RequestParam("fileInput") MultipartF
byte[] bytes = PdfUtils.convertToPdf(file.getInputStream());
logger.info("File {} successfully converted to pdf", file.getOriginalFilename());

return PdfUtils.bytesToWebResponse(bytes, file.getName() + "_coverted.pdf");
return PdfUtils.bytesToWebResponse(bytes, file.getOriginalFilename().replaceFirst("[.][^.]+$", "")+ "_coverted.pdf");
}

@PostMapping("/pdf-to-img")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package stirling.software.SPDF.controller.converters;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.Color;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import stirling.software.SPDF.utils.PdfUtils;

@Controller
public class ConvertXlsxController {


@GetMapping("/xlsx-to-pdf")
public String cinvertToPDF(Model model) {
model.addAttribute("currentPage", "xlsx-to-pdf");
return "convert/xlsx-to-pdf";
}

@PostMapping("/xlsx-to-pdf")
public ResponseEntity<byte[]> convertToPDF(@RequestParam("fileInput") MultipartFile xlsx) throws IOException, DocumentException{
// Load Excel file

Workbook workbook = WorkbookFactory.create(xlsx.getInputStream());

// Create PDF document
Document document = new Document();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PdfWriter.getInstance(document, outputStream);
document.open();

// Convert each sheet in Excel to a separate page in PDF
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
PdfPTable table = new PdfPTable(workbook.getSheetAt(i).getRow(0).getPhysicalNumberOfCells());
for (int row = 0; row < workbook.getSheetAt(i).getPhysicalNumberOfRows(); row++) {
for (int cell = 0; cell < workbook.getSheetAt(i).getRow(row).getPhysicalNumberOfCells(); cell++) {
PdfPCell pdfCell = new PdfPCell();
pdfCell.addElement(new com.itextpdf.text.Paragraph(workbook.getSheetAt(i).getRow(row).getCell(cell).toString()));

// Copy cell style, borders, and background color
pdfCell.setBorderColor(new BaseColor(workbook.getSheetAt(i).getRow(row).getCell(cell).getCellStyle().getBottomBorderColor()));
pdfCell.setBorderColor(new BaseColor(workbook.getSheetAt(i).getRow(row).getCell(cell).getCellStyle().getTopBorderColor()));
pdfCell.setBorderColor(new BaseColor(workbook.getSheetAt(i).getRow(row).getCell(cell).getCellStyle().getLeftBorderColor()));
pdfCell.setBorderColor(new BaseColor(workbook.getSheetAt(i).getRow(row).getCell(cell).getCellStyle().getRightBorderColor()));
Short bc = workbook.getSheetAt(i).getRow(row).getCell(cell).getCellStyle().getFillBackgroundColor();
pdfCell.setBackgroundColor(new BaseColor(bc));

table.addCell(pdfCell);
}
}
document.add(table);
}
// Close document and output stream
document.close();
outputStream.flush();
outputStream.close();
return PdfUtils.boasToWebResponse(outputStream, xlsx.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_convertedToPDF.pdf");
// Close document and input stream


}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import java.util.Map;
import java.util.Map.Entry;

import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.springframework.http.ResponseEntity;
Expand Down Expand Up @@ -49,7 +50,7 @@ public ResponseEntity<byte[]> metadata(@RequestParam("fileInput") MultipartFile

// Load the PDF file into a PDDocument
PDDocument document = PDDocument.load(pdfFile.getBytes());

// Get the document information from the PDF
PDDocumentInformation info = document.getDocumentInformation();

Expand All @@ -69,6 +70,9 @@ public ResponseEntity<byte[]> metadata(@RequestParam("fileInput") MultipartFile
for (String key : info.getMetadataKeys()) {
info.setCustomMetadataValue(key, null);
}
// Remove metadata from the PDF history
document.getDocumentCatalog().getCOSObject().removeItem(COSName.getPDFName("Metadata"));
document.getDocumentCatalog().getCOSObject().removeItem(COSName.getPDFName("PieceInfo"));
author = null;
creationDate = null;
creator = null;
Expand Down Expand Up @@ -126,7 +130,7 @@ public ResponseEntity<byte[]> metadata(@RequestParam("fileInput") MultipartFile
info.setTrapped(trapped);

document.setDocumentInformation(info);
return PdfUtils.pdfDocToWebResponse(document, pdfFile.getName() + "_metadata.pdf");
return PdfUtils.pdfDocToWebResponse(document, pdfFile.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_metadata.pdf");
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public String permissionsForm(Model model) {
public ResponseEntity<byte[]> compressPDF(@RequestParam("fileInput") MultipartFile fileInput, @RequestParam(name = "password") String password) throws IOException {
PDDocument document = PDDocument.load(fileInput.getBytes(), password);
document.setAllSecurityToBeRemoved(true);
return PdfUtils.pdfDocToWebResponse(document, fileInput.getName() + "_password_removed.pdf");
return PdfUtils.pdfDocToWebResponse(document, fileInput.getOriginalFilename().replaceFirst("[.][^.]+$", "")+ "_password_removed.pdf");
}

@PostMapping("/add-password")
Expand Down Expand Up @@ -75,7 +75,7 @@ public ResponseEntity<byte[]> compressPDF(@RequestParam("fileInput") MultipartFi

document.protect(spp);

return PdfUtils.pdfDocToWebResponse(document, fileInput.getName() + "_passworded.pdf");
return PdfUtils.pdfDocToWebResponse(document, fileInput.getOriginalFilename().replaceFirst("[.][^.]+$", "")+ "_passworded.pdf");
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,6 @@ public ResponseEntity<byte[]> addWatermark(@RequestParam("fileInput") MultipartF
// Close the content stream
contentStream.close();
}
return PdfUtils.pdfDocToWebResponse(document, pdfFile.getName() + "_watermarked.pdf");
return PdfUtils.pdfDocToWebResponse(document, pdfFile.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_watermarked.pdf");
}
}
32 changes: 32 additions & 0 deletions src/main/java/stirling/software/SPDF/utils/ErrorUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package stirling.software.SPDF.utils;

import java.io.PrintWriter;
import java.io.StringWriter;

import org.springframework.ui.Model;
import org.springframework.web.servlet.ModelAndView;

public class ErrorUtils {

public static Model exceptionToModel(Model model, Exception ex) {
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
String stackTrace = sw.toString();

model.addAttribute("errorMessage", ex.getMessage());
model.addAttribute("stackTrace", stackTrace);
return model;
}

public static ModelAndView exceptionToModelView(Model model, Exception ex) {
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
String stackTrace = sw.toString();

ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("errorMessage", ex.getMessage());
modelAndView.addObject("stackTrace", stackTrace);
return modelAndView;
}

}
15 changes: 15 additions & 0 deletions src/main/java/stirling/software/SPDF/utils/PdfUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.spire.pdf.PdfDocument;

public class PdfUtils {
Expand Down Expand Up @@ -157,6 +160,18 @@ public static byte[] overlayImage(byte[] pdfBytes, byte[] imageBytes, float x, f
}
}

public static ResponseEntity<byte[]> iTextDocToWebResponse(Document document, String docName) throws IOException, DocumentException {
// Close the document
document.close();

// Open Byte Array and save document to it
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos).close();


return PdfUtils.boasToWebResponse(baos, docName);
}

public static ResponseEntity<byte[]> pdfDocToWebResponse(PdfDocument document, String docName) throws IOException {

// Open Byte Array and save document to it
Expand Down
6 changes: 6 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,9 @@ spring.servlet.multipart.max-file-size=1000MB
spring.servlet.multipart.max-request-size=1000MB

server.forward-headers-strategy=NATIVE

server.error.path=/error
server.error.whitelabel.enabled=false
server.error.include-stacktrace=always
server.error.include-exception=true
server.error.include-message=always
19 changes: 19 additions & 0 deletions src/main/resources/messages_ar_AR.properties
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ home.addImage.desc=إضافة صورة إلى موقع معين في PDF (الع
home.watermark.title=إضافة علامة مائية
home.watermark.desc=أضف علامة مائية مخصصة إلى مستند PDF الخاص بك.

home.remove-watermark.title = \u0625\u0632\u0627\u0644\u0629 \u0627\u0644\u0639\u0644\u0627\u0645\u0629 \u0627\u0644\u0645\u0627\u0626\u064A\u0629
home.remove-watermark.desc = \u0625\u0632\u0627\u0644\u0629 \u0627\u0644\u0639\u0644\u0627\u0645\u0627\u062A \u0627\u0644\u0645\u0627\u0626\u064A\u0629 \u0645\u0646 \u0645\u0633\u062A\u0646\u062F PDF \u0627\u0644\u062E\u0627\u0635 \u0628\u0643.

home.permissions.title=تغيير الأذونات
home.permissions.desc=قم بتغيير أذونات مستند PDF الخاص بك

Expand All @@ -72,6 +75,9 @@ home.compressPdfs.desc=ضغط ملفات PDF لتقليل حجم الملف.
home.changeMetadata.title = \u062A\u063A\u064A\u064A\u0631 \u0627\u0644\u0628\u064A\u0627\u0646\u0627\u062A \u0627\u0644\u0648\u0635\u0641\u064A\u0629
home.changeMetadata.desc = \u062A\u063A\u064A\u064A\u0631 / \u0625\u0632\u0627\u0644\u0629 / \u0625\u0636\u0627\u0641\u0629 \u0628\u064A\u0627\u0646\u0627\u062A \u0623\u0648\u0644\u064A\u0629 \u0645\u0646 \u0645\u0633\u062A\u0646\u062F PDF

home.xlsToPdf.title = \u062A\u062D\u0648\u064A\u0644 Excel (Xls) \u0625\u0644\u0649 PDF
home.xlsToPdf.desc = \u0642\u0645 \u0628\u062A\u062D\u0648\u064A\u0644 \u0645\u0633\u062A\u0646\u062F Excel (xls \u060C xlsx) \u0625\u0644\u0649 PDF.

#Add image
addImage.title=إضافة صورة
addImage.header=إضافة صورة إلى PDF (العمل قيد التقدم)
Expand Down Expand Up @@ -172,6 +178,12 @@ watermark.selectText.5=widthSpacer (مسافة بين كل علامة مائية
watermark.selectText.6=heightSpacer (مسافة بين كل علامة مائية عموديًا):
watermark.submit=إضافة علامة مائية

#remove-watermark
remove-watermark.title = \u0625\u0632\u0627\u0644\u0629 \u0627\u0644\u0639\u0644\u0627\u0645\u0629 \u0627\u0644\u0645\u0627\u0626\u064A\u0629
remove-watermark.header = \u0625\u0632\u0627\u0644\u0629 \u0627\u0644\u0639\u0644\u0627\u0645\u0629 \u0627\u0644\u0645\u0627\u0626\u064A\u0629
remove-watermark.selectText.1 = \u062D\u062F\u062F PDF \u0644\u0625\u0632\u0627\u0644\u0629 \u0627\u0644\u0639\u0644\u0627\u0645\u0629 \u0627\u0644\u0645\u0627\u0626\u064A\u0629 \u0645\u0646:
remove-watermark.selectText.2 = \u0646\u0635 \u0627\u0644\u0639\u0644\u0627\u0645\u0629 \u0627\u0644\u0645\u0627\u0626\u064A\u0629:
remove-watermark.submit = \u0625\u0632\u0627\u0644\u0629 \u0627\u0644\u0639\u0644\u0627\u0645\u0629 \u0627\u0644\u0645\u0627\u0626\u064A\u0629

#Change permissions
permissions.title=تغيير الأذونات
Expand Down Expand Up @@ -213,3 +225,10 @@ changeMetadata.trapped = \u0645\u062D\u0627\u0635\u0631:
changeMetadata.selectText.4 = \u0628\u064A\u0627\u0646\u0627\u062A \u0648\u0635\u0641\u064A\u0629 \u0623\u062E\u0631\u0649:
changeMetadata.selectText.5 = \u0625\u0636\u0627\u0641\u0629 \u0625\u062F\u062E\u0627\u0644 \u0628\u064A\u0627\u0646\u0627\u062A \u0623\u0648\u0644\u064A\u0629 \u0645\u062E\u0635\u0635
changeMetadata.submit = \u062A\u063A\u064A\u064A\u0631



xlsToPdf.title = \u062A\u062D\u0648\u064A\u0644 Excel \u0625\u0644\u0649 PDF
xlsToPdf.header = \u062A\u062D\u0648\u064A\u0644 Excel \u0625\u0644\u0649 PDF
xlsToPdf.selectText.1 = \u062D\u062F\u062F \u0648\u0631\u0642\u0629 \u0625\u0643\u0633\u0644 XLS \u0623\u0648 XLSX \u0644\u0644\u062A\u062D\u0648\u064A\u0644
xlsToPdf.convert = \u062A\u062D\u0648\u064A\u0644
18 changes: 16 additions & 2 deletions src/main/resources/messages_de_DE.properties
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ home.addImage.desc=Fügt ein Bild an eine bestimmte Stelle im PDF ein (Work in p
home.watermark.title=Wasserzeichen hinzufügen
home.watermark.desc=Fügen Sie ein eigenes Wasserzeichen zu Ihrem PDF hinzu.

home.remove-watermark.title=Wasserzeichen entfernen
home.remove-watermark.desc=Wasserzeichen aus Ihrem PDF-Dokument entfernen.

home.permissions.title=Berechtigungen ändern
home.permissions.desc=Die Berechtigungen für Ihr PDF-Dokument verändern.

Expand All @@ -68,6 +71,9 @@ home.compressPdfs.desc=PDF komprimieren um die Dateigröße zu reduzieren.
home.changeMetadata.title=Metadaten ändern
home.changeMetadata.desc=Ändern/Entfernen/Hinzufügen von Metadaten aus einem PDF-Dokument

home.xlsToPdf.title=Excel (Xls) in PDF
home.xlsToPdf.desc=Konvertiere ein Excel-Dokument (xls, xlsx) in PDF.

#Add image
addImage.title=Bild hinzufügen
addImage.header=Ein Bild einfügen (Work in progress)
Expand All @@ -88,7 +94,6 @@ merge.submit=Zusammenführen
#pdfOrganiser
pdfOrganiser.title=Seiten anordnen
pdfOrganiser.header=PDF Seitenorganisation
#pdfOrganiser.pagesToOrganize=Seitenanordnung (geben Sie eine Kommagetrennte Liste der Seitenzahlen an): # may have forgotten to add this as a translation option?
pdfOrganiser.submit=Seiten anordnen


Expand Down Expand Up @@ -169,6 +174,12 @@ watermark.selectText.5=breiteSpacer (horizontaler Abstand zwischen den einzelnen
watermark.selectText.6=höheSpacer (vertikaler Abstand zwischen den einzelnen Wasserzeichen):
watermark.submit=Wasserzeichen hinzufügen

#remove-watermark
remove-watermark.title=Wasserzeichen entfernen
remove-watermark.header=Wasserzeichen entfernen
remove-watermark.selectText.1=PDF auswählen, um Wasserzeichen zu entfernen von:
remove-watermark.selectText.2=Wasserzeichentext:
remove-watermark.submit=Wasserzeichen entfernen

#Change permissions
permissions.title=Berechtigungen ändern
Expand Down Expand Up @@ -214,7 +225,10 @@ changeMetadata.submit=




xlsToPdf.title=Excel in PDF
xlsToPdf.header=Excel in PDF
xlsToPdf.selectText.1=XLS- oder XLSX-Excel-Tabelle zum Konvertieren auswählen
xlsToPdf.convert=konvertieren



Expand Down
Loading

0 comments on commit 67345d0

Please sign in to comment.