Converting .doc to .pdf in java (for free) - pdf

I created a java app that create some documents in output. The documents are created with apache POI api and are made of text abn tables.
My boss now decided they also want them in pdf format for storing them. They of course have 0$ budget. I tryed using iText 4.2 (which comes under lgpl license) but i lost all tables (I'm having only naked text)
This is my script:
try{
XWPFDocument doc = new XWPFDocument(POIXMLDocument.openPackage(s + ".doc"));
XWPFWordExtractor wx = new XWPFWordExtractor(doc);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(s + ".pdf"));
document.open();
writer.setPageEmpty(true);
document.newPage();
writer.setPageEmpty(true);
String text = wx.getText();
text=text.replaceAll("\\cM?\r?\n", "");
document.add(new Paragraph(text));
}
catch(Exception e){
System.out.println("Exception during test");
e.printStackTrace();
}
Any help? Even a change of direction would be great. I was wandering if I could simply write a macro that open the doc, type save as, and save it as pdf with same name. Launching it eventually inside java app.
Thank you

You might want to take a look at this, pretty similar question.
I wrote an answer there which is not tested yet since i got no time to do so. But it might sill solve your problem or atleast give you some hints for further researches.

Related

How to (actually) load RichTextBox from VB.NET in VS2022

Have spent hours on hours exploring "solutions" that surely worked for someone, sometime, somewhere.
Alas NONE seem to work when I try to do so creating a Windows Desktop App using VB.NET in VS2022. Has something changed? Am I just plain dense.
Tried the obvious... RichTextBox1.Text = File.ReadAllText("C:\Temp\Results.txt"), followed by several alternatives, e.g. moving the file to the \bin file of the code etc. ALL futile.
Will TRY to add screen shots of significant issues, e.g. does the file exist... I say try because haven't yet learned how to deal with the "add Text File where stateda picture: feature, beyond adding only one.
Text file content in Notepad
Simple Code that fails
This is C# code if you Google C# to VB.Net you will find a code converter
Now that you have the naming issue solved and the Path correct This code will load txt data to a listBox just change the name for your RichTextBox
You might like to consider SQLite if you want to store data much better!
private void btnMakeDB_Click(object sender, EventArgs e)
{
listBox.Items.Clear();
using (StreamReader sr = new StreamReader(path))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
listBox.Items.Add(line);
textBox.Text = line;
}
}
}

iText 7 Chinese characters and merge with existing pdf template

I have to rephrase my question, basically my request is very straight forward, i want to display Asian characters in the generated pdf file from iText7.
As of now i have download the NotoSansCJKsc-Regular.otf file and assign a variable to hold the path, below is my code:
public static string FONT = #"D:\Projects\Resources\NotoSansCJKsc-Regular.otf";
PdfWriter writer = new PdfWriter(#"C:\temp\test.pdf");
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc, PageSize.A4);
PdfFont fontChinese = PdfFontFactory.CreateFont(FONT, PdfEncodings.IDENTITY_H);
doc.SetFont(fontChinese);
but the issue i am facing now is whenever the code runs to this section:
PdfFont fontChinese = PdfFontFactory.CreateFont(FONT, PdfEncodings.IDENTITY_H);
i am always getting this error: The request could not be performed because of an I/O device error. and this error doesn't make sense to me and I am struggling to find out the solution, could someone in here had the similar issue plz, the code is in C#.
Many thanks.
I can confirm that above code is working as expected, the .otf file that I was originally downloaded was corrupted, hence I got above error.

Adobe breaks stamped PDF when saving as new file / what is difference in Adobe 'save as' vs. Foxit Reader 'save as' feature

I'm reaching out to larger community of developers in seek of help to understand the real cause and possibly finding a fix. I have asked questions from Aspose, and they have also tracked the issue (PDFNET-42880) in their system. I think they are not going to investigate this anytime soon as it is very specific case. And now I am posting this here to ask more details about:
What is difference in Adobe 'save as' vs. Foxit Reader 'save as' vs. Windows Reader 'save as' feature?
Issues with Adobe product that are not so obvious to figure out. I don't even know what to ask :D
Link to their (Aspose) old forum: https://www.aspose.com/community/forums/thread/845549/removing-stamps-fails-after-saving-stamped-file-from-adobe-acrobat.aspx
Case:
Created PDF with forms using OpenOffice (version 3.4.0), stamped with Aspose PDF, opened with Adobe Reader DC (or Adobe Acrobat XI), filled, saved as new file. Now this new file is fine, but when I try to remove stamps using Aspose (and replace with new stamp later), this is where things get interesting.
Files that I've tested with: https://1drv.ms/f/s!Auvpijam7a73iDzOqc6wZPuY9l81
Stamp_Location.png
OoPdfFormExample_WithStamp.pdf
OoPdfFormExample_WithStamp_StampRemoved.pdf
OoPdfFormExample_WithStamp_SavedFromFoxit.pdf
OoPdfFormExample_WithStamp_SavedFromFoxit_StampRemoved.pdf
OoPdfFormExample_WithStamp_SavedFromWindowsReader.pdf
OoPdfFormExample_WithStamp_SavedFromWindowsReader_StampRemoved.pdf
OoPdfFormExample_WithStamp_SavedFromAdobeReader.pdf
OoPdfFormExample_WithStamp_SavedFromAcrobat_StampRemoved.pdf
C# code that is used to remove the stamp(s):
/// <summary>
/// Removes stamps from PDF file.
/// </summary>
/// <param name="pdfFile"></param>
private static void RemoveStamps( string pdfFile )
{
// Create PDF content editor.
Aspose.Pdf.Facades.PdfContentEditor contentEditor = new Aspose.Pdf.Facades.PdfContentEditor();
// Open the temp file.
contentEditor.BindPdf( pdfFile );
// Process all pages.
foreach ( Page page in contentEditor.Document.Pages )
{
// Get the stamp infos.
Aspose.Pdf.Facades.StampInfo[] stampInfos = contentEditor.GetStamps( page.Number );
//Process all stamp infos
foreach ( Aspose.Pdf.Facades.StampInfo stampInfo in stampInfos )
{
// Use try catch so we can output possible error w/out break point.
try
{
contentEditor.DeleteStampById( stampInfo.StampId );
}
catch ( Exception e )
{
Console.WriteLine( e );
}
}
}
// Save changes to the temp file.
contentEditor.Save( StampRemovedPdfFile );
}
Using Adobe: The process of removing stamp works fine, but trying to open the file will end up having an issue with the file.
"An error exists on this Page. Acrobat may not display the page correctly. Please contact the person who created the PDF document to correct the problem."
EDIT: After testing more, and just opening file to Aspose, and saving it without modifications, that didn't break the file, only once the stamp was removed with Aspose method it was broken.
Using Foxit: Only difference in the process is that opening the file to Foxit Reader and save form there. The stamp is removed and file is fine, works with any PDF reader.
Using Windows (10) Reader: Only difference in the process is that opening the file to Windows Reader and save from there. The stamp is removed and file is fine, works with any PDF reader.
Ok - The thing you are referring to is not a stamp annotation. It's an XObject that gets drawn into the page content. Why Aspose refers to it as a Stamp is... well... a mystery. When you remove the "stamp" (not a stamp) Aspose seems to be removing the XObject but not the instructions to draw it from the page Contents stream... that's why you're getting the error in Acrobat. The other applications are more permissive with bad PDF and my guess is when they write out the file, they are removing references to non-existent objects. You can make Acrobat attempt to fix problems like this by selecting Save As Optimized PDF. However, you are far better off removing the drawing instruction in addition to the XObject.
Because of the way you've created the file and added the "stamp", your page content stream is an array of streams. Remove the last item in the array, which is the instruction to draw the XObject, and you file will work without errors in all the viewers. Note: It won't always be the case that the last item in the content array will be your stamp. It's just that your stamp is the last thing to get drawn so it goes at the end.
If your intention is to "replace" the "stamp", you'll want to do so by removing the XObject as you are doing now, then remove the instruction, then add the new "stamp".

Remove PDFont caching with Apache tika

I am trying to extract text only from a number of different coduments (rtf doc pdf). I naturally turned to Apache Tika because it can autodetect the document and extract text accordingly. I am only interested in the text and not formatting etc.
My application ends up with a big memory leak and on investigating it, this is coming from caching from PDFFont class from the PDFBox dependency. I am not interesting in caching Fontmetrics and other Font formatting issues from pdfs as I want to only extract the text.
I am using tika 1.12. Does anyone know how to get around this cahcing issue. This is how I am using Autodetect:
AutoDetectParser parser = new AutoDetectParser();
BodyContentHandler handler = new BodyContentHandler(-1);
Metadata metadata = new Metadata();
FileInputStream inputstream = new FileInputStream(new File(child.getPath()));
ParseContext context = new ParseContext();
parser.parse(inputstream, handler, metadata, context);
String s=null;
s =handler.toString();
handler=null;
context=null;
inputstream.close();
PDFont.clearResources();
So I fudged a workaround and just called System.gc(); everytime the file had finished being processed which works a treat but doesn't really answer the question.

GhostScript .NET not continuing past certain pages

I've created a program which needs to convert PDF files into image files, and for this GhostScript is the best choice. But once in a while, the library stalls completely on a page and doesn't continue, it just keeps using CPU power and working, as though it might be caught in an infinite loop. The error is easily reproduce-able as it happens every time on the specific PDF files that it occurs on, though no error is given from GhostScript of any kind, and nothing is out of the ordinary in the PDF files themselves as far as I can see.
I have however been able to find out that the stalling is due to a specific element or elements in the pdf files, and by deleting the elements the pdf will easily render in GhostScript, but this is not a solution, nor an answer I can use.
PDF link* - http://www.filedropper.com/usjunis1-32webtest
*saved with free version of PDF-XChange Editor, so it has watermarks at the top, but it is the square that creates the stalling. I've also seen it happen on vector graphics objects, so it is not limited to squares.
Code -
private void startImageProcessing(String pdfFile)
{
GhostscriptVersionInfo gvi = new GhostscriptVersionInfo(new Version(0, 0, 0), Directory.GetCurrentDirectory() + #"\gsdll32.dll", string.Empty, GhostscriptLicense.GPL);
Ghostscript.NET.Processor.GhostscriptProcessor processor = new Ghostscript.NET.Processor.GhostscriptProcessor(gvi, true);
processor.StartProcessing(CreateTestArgs(pdfFile, pdfFile.Substring(0, pdfFile.Length - 4) + "\\"+prefix+"-%03d.jpg", 72 * scale), new ConsoleStdIO(true));
}
private static string[] CreateTestArgs(string inputPath, string outputPath, int dpi)
{
List<string> gsArgs = new List<string>();
gsArgs.Add("-dSAFER");
gsArgs.Add("-dBATCH");
gsArgs.Add("-dNOPAUSE");
gsArgs.Add("-sDEVICE=jpeg");
gsArgs.Add("-r" + dpi);
gsArgs.Add("-dJPEGQ=100");
gsArgs.Add("-dNumRenderingThreads=" + Environment.ProcessorCount.ToString());
gsArgs.Add("-dTextAlphaBits=4");
gsArgs.Add("-dGraphicsAlphaBits=4");
gsArgs.Add(#"-sOutputFile=" + outputPath);
gsArgs.Add(#"-f" + inputPath);
return gsArgs.ToArray();
}
I've also created a pdf file only containing one of the wrong elements for testing, and it has both had the error when saved by Adobe Acrobat, and PDF-XChange Editor, so the error is not due to a specific program that I've used to save the PDF either.