error occurred while closing itext stamper - itext

I'm receiving an error when closing itextpdf stamper. Stamper is used for setting password for PDF file. application is deployed in weblogic server. Itextpdf5.5.10 is used.
OutputStream outputStream = null;
try {
PdfReader reader = new PdfReader("/apps/abc.pdf");
System.out.println(reader.getNumberOfPages());
PdfStamper stamper = new PdfStamper(reader, outputStream, '\0');
stamper.setEncryption("abc".getBytes(), "123".getBytes(),
PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA);
stamper.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
Please, help. :(

Related

Error when execute jar file with itextpdf added

I am trying to create a report using itextpdf. Everything is fine when I run the program. But I have a problem if I execute this command java -jar myproject.jar and I have the error below. I already added the itextpdf to the library, I don't understand why I got this error. Could someone explain it to me and show me how to fix this?
Thanks.
Exception in thread "main" java.lang.NoClassDefFoundError: com/itextpdf/text/DocumentException
at xxx.yyy.main(yyy.java:24)
Caused by: java.lang.ClassNotFoundException: com.itextpdf.text.DocumentException
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
The below is my code for creating a pdf file
public void savePDF(String path) throws FileNotFoundException, BadElementException, IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(path);
Document doc = new Document();
doc.setPageSize(PageSize.A4.rotate());
doc.setMargins(50f, 50f, 10f, 10f);
PdfWriter writer = PdfWriter.getInstance(doc, fos);
doc.open();
try {
doc.add(headerTable());
} catch (BadElementException | IOException ex) {
Logger.getLogger(createBeamCalculationsPDF.class.getName()).log(Level.SEVERE, null, ex);
}
addSeparatorLine(doc);
doc.add(generalProperties());
doc.newPage();
doc.close();
writer.close();
fos.close();
} catch (DocumentException ex) {
Logger.getLogger(createBeamCalculationsPDF.class.getName()).log(Level.SEVERE, null, ex);
}
}

Issue in converting HTML to PDF containing <pre> tag with Flying Saucer and ITEXT

I am using Flying Saucer library to convert html to pdf. It is working fine with the all the HTML files.
But for some HTML files which include some tags in pre tag, generated PDF file has tags displayed.
If I remove pre tags then the formatting of data is lost.
My code is
org.w3c.dom.Document document = null;
try {
Document doc = Jsoup.parse(new File(htmlFile), "UTF-8", "");
Whitelist wl = new RelaxedPlusDataBase64Images();
Cleaner cleaner = new Cleaner(wl);
doc = cleaner.clean(doc);
Tidy tidy = new Tidy();
tidy.setShowWarnings(false);
tidy.setXmlTags(false);
tidy.setInputEncoding("UTF-8");
tidy.setOutputEncoding("UTF-8");
tidy.setPrintBodyOnly(true);
tidy.setXHTML(true);
tidy.setMakeClean(true);
tidy.setAsciiChars(true);
if (doc.select("pre").html().contains("</")) {
doc.select("pre").unwrap();
}
Reader reader = new StringReader(doc.html());
document = (tidy.parseDOM(reader, null));
Element element = (Element) document.getElementsByTagName("head").item(0);
element.getParentNode().removeChild(element);
NodeList elements = document.getElementsByTagName("img");
for (int i = 0; i < elements.getLength(); i++) {
String value = elements.item(i).getAttributes().getNamedItem("src").getNodeValue();
if (value != null && value.startsWith("cid:") && value.contains("#")) {
value = value.substring(value.indexOf("cid:") + 4, value.indexOf("#"));
elements.item(i).getAttributes().getNamedItem("src").setNodeValue(value);
System.out.println(value);
}
}
document.normalize();
System.out.println(getNiceLyFormattedXMLDocument(document));
} catch (Exception e) {
System.out.println(e);
}
Method to create PDF is :
try {
org.w3c.dom.Document doc = CleanHtml.cleanNTidyHTML("b.html");
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(doc, null);
renderer.setPDFVersion(new Character('7'));
String outputFile = "test.pdf";
OutputStream os = new FileOutputStream(outputFile);
renderer.layout();
renderer.createPDF(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
By using itext XMLWorker :
try {
org.w3c.dom.Document doc = CleanHtml.cleanNTidyHTML("a.html");
String k = CleanHtml.getNiceLyFormattedXMLDocument(doc);
OutputStream file = new FileOutputStream(new File("test.pdf"));
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, file);
document.open();
ByteArrayInputStream is = new ByteArrayInputStream(k.getBytes());
XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
document.close();
file.close();
} catch (Exception e) {
e.printStackTrace();
}
public static String getNiceLyFormattedXMLDocument(org.w3c.dom.Document doc) throws IOException, TransformerException {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
// transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
Writer stringWriter = new StringWriter();
StreamResult streamResult = new StreamResult(stringWriter);
transformer.transform(new DOMSource(doc), streamResult);
String result = stringWriter.toString();
return result;
}

Strange characters in the title of an alert, possible encoding issue?

I trying to write simple method that shows alert dialog and ask user for feedback on my email.
My method:
public static void showExceptionDialog(Exception exception) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
exception.printStackTrace(printWriter);
String exceptionText = stringWriter.toString();
try {
VBox content = FXMLLoader.load(Dialogs.class.getResource("/org/flycraft/minecraft/droplauncher/exception_dialog_content.fxml"));
TextArea exceptionTextArea = (TextArea) content.lookup("#exception_text_area");
exceptionTextArea.setText(exceptionText);
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Ошибка");
alert.setHeaderText("Что-то пошло не так");
alert.getDialogPane().setContent(content);
alert.showAndWait();
} catch (IOException e) {
e.printStackTrace();
}
}
But in real dialog i see:
This is a bug, or something I don't understand?
Yep, fixed. I use this plugin for building JavaFX application with gradle. So I just added this line to my build.gradle:
compileJava.options.encoding = 'UTF-8'

Unity giving errors that aren't there?

I am using unity to connect to a server using this code attached to a button click, but I am getting a lot of errors that there aren't semicolons? Why am I getting these errors?
public function BTN_Connect() {
String message;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 5552);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
message = inFromServer.readLine();
System.out.println("FROM SERVER: " + message);
clientSocket.close();
}

How use itext to change existing pdf pagesize?

I have a pdf, but beyond the current page, there is content that is not being displayed. I want to change the pagesize so that all of the content can be displayed. Is there a way to do this with itext?
public PdfReader changePDFPageSize(String inpdf,String outpdf,float vertical,float horizontal)
{
try
{
PdfReader reader = new PdfReader(inpdf);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outpdf));
for (int curPageNum = 1; curPageNum <= reader.getNumberOfPages(); ++curPageNum) {
PdfDictionary pagedict = reader.getPageN(curPageNum);
PdfArray mediabox = pagedict.getAsArray(PdfName.MEDIABOX);
mediabox.set(0, new PdfNumber(mediabox.getAsNumber(0).intValue()-horizontal));//left add
mediabox.set(1, new PdfNumber(mediabox.getAsNumber(1).intValue()-vertical));//down
mediabox.set(2, new PdfNumber(mediabox.getAsNumber(2).intValue()+horizontal));//right
mediabox.set(3, new PdfNumber(mediabox.getAsNumber(3).intValue()+vertical));//up
}
stamper.close();
return new PdfReader(outpdf);
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (DocumentException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return null;
}
itextsharp VB.NET
Dim objReader As PdfReader
Dim objStream As FileStream
Dim objStamper As PdfStamper
Dim objContent As PdfContentByte
Dim objImport As PdfImportedPage
Dim objMark As Image
objReader = New PdfReader(strBookPath)
objStream = New FileStream(strTempPath, FileMode.Create)
objStamper = New PdfStamper(objReader, objStream)
objContent = objStamper.GetOverContent(1)
objImport = objStamper.GetImportedPage(objReader, 1)
objContent.AddTemplate(objImport, PageSize.A4.Width / objImport.Width, 0, 0, PageSize.A4.Height / objImport.Height, 0, 0)
objReader.GetPageN(1).Put(PdfName.CROPBOX, New PdfRectangle(PageSize.A4.Width, PageSize.A4.Height))
objReader.GetPageN(1).Put(PdfName.MEDIABOX, New PdfRectangle(PageSize.A4.Width, PageSize.A4.Height))