spring boot i text errror - spring-boot

hi guys I have an existing pdf file that contain facture body I want to add text to this facture, I made a testing code to test how it works, but the code I wrote delete my original file and as a result the added text
private static final String FILE_PATH_NAME = "./src/main/resources/educart.pdf";
public void exportpdf(facture fact) {
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(new File(FILE_PATH_NAME)));
//open
document.open();
// Paragraph 1 ->
Paragraph p = new Paragraph("This is a paragraph 1",
FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLDITALIC));
document.add(p);
// Paragraph 2 ->
Paragraph p2 = new Paragraph();
p2.add("This is a paragraph 2");
p2.setAlignment(Element.ALIGN_CENTER);
document.add(p2);
// Paragraph 3 ->
Font f = new Font();
f.setStyle(Font.BOLD);
f.setSize(30);
f.setColor(255, 0, 0);
Paragraph p3 = new Paragraph("This is a paragraph 3", f);
p3.setAlignment(Element.ALIGN_RIGHT);
document.add(p3);
// Paragraph 4 ->
Paragraph p4 = new Paragraph("Grokonez",
FontFactory.getFont(FontFactory.HELVETICA, 250, Font.BOLDITALIC));
document.add(p4);
// Finish task ->
document.close();
System.out.println("Finish!");
} catch (DocumentException | FileNotFoundException e) {
e.printStackTrace();
}
}
orignal pdf file
result

PdfReader pdfReader =
new PdfReader("./src/main/resources/educart.pdf");
//Create PdfStamper instance.
PdfStamper pdfStamper = new PdfStamper(pdfReader, out);

Related

Filling XFA data to xfa form pdf with ITEXT 7 in C#

PdfReader reader = new PdfReader(sourceXfaPath);
PdfWriter writer = new PdfWriter(exportPdf);
PdfDocument pdfDoc = new PdfDocument(reader, writer, new StampingProperties().UseAppendMode());
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
XfaForm xfa = form.GetXfaForm();
xfa.FillXfaForm(new FileStream(exportXfaXml,FileMode.Open));
xfa.Write(pdfDoc);
pdfDoc.Close();
reader.Close();
codes are above:
but it doesn't create pdf document, I'm not sure why it doesn't create it.
I just tried xfa.FillXfaForm(new FileStream(exportXfaXml,FileMode.Open)); to xfa.FillXfaForm(XmlReader.Create(path));
but it shows me same error
public void customGenerate(string sourceFilePath, string destinationtFilePath, string replacementXmlFilePath)
{
PdfReader pdfReader = new PdfReader(sourceFilePath);
using (MemoryStream ms = new MemoryStream())
{
using (PdfStamper stamper = new PdfStamper(pdfReader, ms, '\0', true))
//using (PdfStamper stamper = new PdfStamper(pdfReader, ms))
{
XfaForm xfaForm = new XfaForm(pdfReader);
XmlDocument doc = new XmlDocument();
doc.Load(replacementXmlFilePath);
xfaForm.DomDocument = doc;
xfaForm.Changed = true;
XfaForm.SetXfa(xfaForm, stamper.Reader, stamper.Writer);
stamper.Close();
}
var bytes = ms.ToArray();
System.IO.File.WriteAllBytes(destinationtFilePath, bytes);
ms.Close();
}
pdfReader.Close();
}
This is my code to add Javacript to XFA PDF.
I'm going to add JavaScript[handle button , checkbox] to XFA pdf with avoid signature.

Insert an image into an existing pdf document using iText Sharp

I need to insert an image into an existing pdf at a specific location. I tried the answer at this question. But whatever different ways I do the image is being inserted at (0,0) position (bottom left corner). I tried another approach where instead of using stream I used Document class in iTextSharp as shown here. Now I am able to place the image at the desired position but this method is creating a new document with just this image. Most of the articles I searched are using PdfReader and PdfStamper so I think this is the recommended way. Any help is appreciated. Posting below code for both the methods I tried.
PdfStamper method
private void AddImage(string filePath)
{
string imageURL = #"ImagePath\Image.jpg";
using (Stream inputPdfStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using (Stream inputImageStream = new FileStream(imageURL, FileMode.Open, FileAccess.Read))
using (Stream outputPdfStream = new FileStream(#"ResultingPdfPath\Abcd.pdf", FileMode.Create, FileAccess.ReadWrite))
{
Image image = Image.GetInstance(inputImageStream);
image.ScaleToFit(100, 100);
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
PdfContentByte content = stamper.GetUnderContent(1);
image.SetAbsolutePosition(100f, 150f);
content.AddImage(image);
stamper.Close();
reader.Close();
}
}
Document class method
private void TestMessage(string filePath)
{
string imageURL = #"ImagePath\Image.jpg";
Document doc = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Open));
doc.Open();
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL);
jpg.ScaleToFit(140f, 120f);
jpg.SetAbsolutePosition(100, 100);
jpg.SpacingBefore = 10f;
jpg.SpacingAfter = 1f;
jpg.Alignment = Element.ALIGN_LEFT;
doc.Add(jpg);
doc.Close();
}
Let me know if you need further information.
I adapted your method to accept variable out paths and positions and tested it with iTextSharp 5.5.7 like this:
[TestFixture]
class TestInsertImage
{
/// iText stamp image on top not always working
/// http://stackoverflow.com/questions/33898280/itext-stamp-image-on-top-not-always-working
///
[Test]
public void AddStampToTestPdf()
{
Directory.CreateDirectory(#"C:\Temp\test-results\content\");
AddImage(#"d:\Issues\stackoverflow\iText stamp image on top not always working\Multipage.pdf", #"C:\Temp\test-results\content\Multipage-stamp-Image-100-150.pdf", 100f, 150f);
AddImage(#"d:\Issues\stackoverflow\iText stamp image on top not always working\Multipage.pdf", #"C:\Temp\test-results\content\Multipage-stamp-Image-150-100.pdf", 150f, 100f);
}
private void AddImage(string filePath, string outPath, float x, float y)
{
string imageURL = #"c:\Repo\GitHub\testarea\itext5\src\test\resources\mkl\testarea\itext5\layer\Willi-1.jpg";
using (Stream inputPdfStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using (Stream inputImageStream = new FileStream(imageURL, FileMode.Open, FileAccess.Read))
using (Stream outputPdfStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
{
Image image = Image.GetInstance(inputImageStream);
image.ScaleToFit(100, 100);
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
PdfContentByte content = stamper.GetUnderContent(1);
image.SetAbsolutePosition(x, y);
content.AddImage(image);
stamper.Close();
reader.Close();
}
}
}
The results are included below.
As you see, the positioning information clearly are respected, and the image is definitely not always at the bottom left corner.
If this indeed does not work for the OP, he is keeping information from us required to help him.
Multipage-stamp-Image-100-150.pdf
Created using
AddImage(#"d:\Issues\stackoverflow\iText stamp image on top not always working\Multipage.pdf", #"C:\Temp\test-results\content\Multipage-stamp-Image-100-150.pdf", 100f, 150f);
Multipage-stamp-Image-150-100.pdf
Created using:
AddImage(#"d:\Issues\stackoverflow\iText stamp image on top not always working\Multipage.pdf", #"C:\Temp\test-results\content\Multipage-stamp-Image-150-100.pdf", 150f, 100f);

ABCPDF 8 - How do I create a layered PDF

I need to use ABCPDF to create a layered PDF file. I've seen examples for watermarks but I need to have a PDF be the second layer. My code is below. When I run it, I only see one layer. What am I doing incorrectly?
Thank you.
WebSupergoo.ABCpdf8.Doc artworkDoc = new WebSupergoo.ABCpdf8.Doc();
artworkDoc.SetInfo(0, "License", _License);
WebSupergoo.ABCpdf8.Doc cutDoc = new WebSupergoo.ABCpdf8.Doc();
cutDoc.SetInfo(0, "License", _License);
// Attempt to read in Artwork File
try
{
artworkDoc.Read(ArtworkPath);
}
catch (Exception ex)
{
Exception noartwork = new Exception("Problem with Artwork File: " + ex.ToString());
throw noartwork;
}
// Attempt to read in cut File
try
{
cutDoc.Read(cutPath);
}
catch (Exception ex)
{
Exception nocut = new Exception("Problem with cut File: " + ex.ToString());
throw nocut;
}
WebSupergoo.ABCpdf8.Doc outputDoc = artworkDoc;
outputDoc.SetInfo(0, "License", _License);
// Attempt to merge artwork and cut files into output Document
try
{
outputDoc.PageNumber = 1;
outputDoc.Layer = outputDoc.LayerCount + 1;
outputDoc.AddImageDoc(cutDoc, 1, outputDoc.Rect);
}
catch (Exception ex)
{
Exception problem = new Exception("Problem appending cut and artwork files to output: " + ex.ToString());
throw problem;
}
// Attempt to save the output Document to the specified output path
try
{
outputDoc.Save(OutputPath);
artworkDoc.Clear();
cutDoc.Clear();
outputDoc.Clear();
}
catch (Exception ex)
{
Exception invalidOutput = new Exception("Unable to write output file: " + ex.ToString());
throw invalidOutput;
}
return true;
}
After resorting to using iTextSharp for some other PDF layer issues I had, I decided to explore how to use iTextSharp to create a new layered PDF file where the layers are pages from existing PDF files. The below code is what I came up with. The code presumes each of the source PDF files only has one page to add as a layer to the new PDF. It took me awhile to figure out so hopefully posting it here will help save others some time.
try
{
iTextSharp.text.pdf.PdfReader artwork = new iTextSharp.text.pdf.PdfReader(#”c:\artwork.pdf”);
iTextSharp.text.pdf.PdfReader cut = new iTextSharp.text.pdf.PdfReader(#”c:\cut.pdf”);
//get size of the cut PDF so the new layered PDF will be sized the same.
iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(cut.GetPageSize(1).Width, cut.GetPageSize(1).Height);
//the artwork PDF needs to be sized the same as the cut pdf
if (artwork.GetPageSize(1).Width != pageSize.Width || artwork.GetPageSize(1).Height != pageSize.Height)
{
string resizedFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(textBox1.Text),System.IO.Path.GetFileNameWithoutExtension(textBox1.Text) + "_resized.pdf");
iTextSharp.text.Document resizedArtwork = new iTextSharp.text.Document(pageSize);
iTextSharp.text.pdf.PdfWriter resizedWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(resizedArtwork, new System.IO.FileStream(resizedFile, System.IO.FileMode.Create));
iTextSharp.text.pdf.PdfImportedPage importedPage = resizedWriter.GetImportedPage(artwork, 1);
resizedArtwork.Open();
iTextSharp.text.pdf.PdfContentByte resizedContentByte = resizedWriter.DirectContent;
resizedContentByte.AddTemplate(importedPage, 0, 0);
resizedArtwork.Close();
//close reader associated with non-resized document
artwork.Close();
//set reader to resized document
artwork = new iTextSharp.text.pdf.PdfReader(resizedFile);
}
//create a new PDF
string outputFileName = #”c:\layered.pdf”;
iTextSharp.text.Document newPDF = new iTextSharp.text.Document(pageSize);
//create writer to output new PDF's contents to
iTextSharp.text.pdf.PdfWriter pdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(newPDF, new System.IO.FileStream(outputFileName,System.IO.FileMode.Create));
//grab the first page from the artwork and cut PDF. These will become new layers in the new PDF
iTextSharp.text.pdf.PdfImportedPage artworkImportedPage = pdfWriter.GetImportedPage(artwork, 1);
iTextSharp.text.pdf.PdfImportedPage cutImportedPage = pdfWriter.GetImportedPage(cut, 1);
newPDF.Open();
iTextSharp.text.pdf.PdfContentByte pdfContentByte = pdfWriter.DirectContent;
pdfContentByte.BeginLayer(new iTextSharp.text.pdf.PdfLayer("artwork",pdfWriter));
pdfContentByte.AddTemplate(artworkImportedPage, 0, 0);
pdfContentByte.EndLayer();
pdfContentByte.BeginLayer(new iTextSharp.text.pdf.PdfLayer("cut", pdfWriter));
pdfContentByte.AddTemplate(cutImportedPage, 0, 0);
pdfContentByte.EndLayer();
newPDF.Close();
pdfWriter.Close();
artwork.Close();
cut.Close();
}
catch (Exception ex)
{
}

iTextSharp - Add image to PDF from Datatable

I try to create a PDF report from a datatable. One of the columns contents image. How can I extract the image from datatable and insert into PDF table? I'm using iTextShap version 5.4.2.0. Here is the code:
public void Report(DataTable dt, string output)
{
Document doc = new Document(PageSize.LETTER, 50, 50, 80, 50);
PdfWriter PDFWriter = PdfWriter.GetInstance(doc, new FileStream(output, FileMode.Create));
PDFWriter.ViewerPreferences = PdfWriter.PageModeUseOutlines;
iTextSharp.text.Font hel8 = FontFactory.GetFont(BaseFont.HELVETICA, 8);
doc.Open();
PdfPTable table = new PdfPTable(dt.Columns.Count);
float[] widths = new float[] { 1.2f, 1.2f, 1.2f, 1.2f, 1f, 4f, 1f, 4f };
table.SetWidths(widths);
table.WidthPercentage = 100;
PdfPCell cell = new PdfPCell(new Phrase("NewCells"));
cell.Colspan = dt.Columns.Count;
foreach (DataColumn c in dt.Columns)
{
table.AddCell(new Phrase(c.ColumnName, hel8));
}
foreach (DataRow r in dt.Rows)
{
if (dt.Rows.Count > 0)
{
table.AddCell(new Phrase(r[0].ToString(), hel8));
table.AddCell(new Phrase(r[1].ToString(), hel8));
table.AddCell(new Phrase(r[2].ToString(), hel8));
table.AddCell(new Phrase(r[3].ToString(), hel8));
table.AddCell(new Phrase(r[4].ToString(), hel8));
table.AddCell(new Phrase(r[5].ToString(), hel8));
byte[] byt = (byte[])r[6];
MemoryStream ms = new MemoryStream(byt);
System.Drwaing.Image sdi = System.Drawing.Image.FromStream(ms);
Image img = Image.GetInstance(sdi); <-- this is the problem code
table.AddCell(img);
table.AddCell(new Phrase(r[7].ToString(), hel8));
}
}
doc.Add(table);
}
doc.Close();
}
Update: #nekno, all of your suggestions are worked.
But I still need to correct the casting at line:
byte[] byt = (byte[])r[6];
It gave me a casting exception from VS2008. So I added the conversion function (pulled it from stackoverflow):
byte[] ImageToByte(System.Drawing.Image img)
{
byte[] byteArray = new byte[0];
using (MemoryStream stream = new MemoryStream())
{
img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Close();
byteArray = stream.ToArray();
}
return byteArray;
}
And revised the code:
byte[] byt = ImageToByte((System.Drawing.Image)dt.Rows[e][6]);
Thanks.
What exactly is the problem? What happens when you use your problem code?
Try one of the other Image.GetInstance() overloads:
You can pass the byte array directly:
byte[] byt = (byte[])r[6];
Image img = Image.GetInstance(byt);
Or you can pass the Stream:
byte[] byt = (byte[])r[6];
MemoryStream ms = new MemoryStream(byt);
Image img = Image.GetInstance(ms);
Or you can give iTextSharp more info about the image format:
byte[] byt = (byte[])r[6];
MemoryStream ms = new MemoryStream(byt);
System.Drawing.Image sdi = System.Drawing.Image.FromStream(ms);
Image img = Image.GetInstance(sdi, ImageFormat.Png);
If your column can be cast to a System.Drawing.Image, then you can use it directly:
Image img = Image.GetInstance((System.Drawing.Image)r[6], System.Drawing.Imaging.ImageFormat.Png);
I have suggested steps how shows how to add image into PDF, given below code snippet show how to add logo into your PDF using iTextsharp, follow provided below steps:
I have provided link to download "itextsharp" component from given link http://sourceforge.net/projects/itextsharp/
You have to add reference into your application.
Next you have to add required namespaces "iTextsharp.text.html", "iTextsharp.text" to consume its best properties.
Now you have to add code snippet into your application given at the end, add code snippet under "button click" in code behind.
Hope it will work for you !!!
protected void btnPDF_Click(object sender, ImageClickEventArgs e)
{
DataTable dtn = new DataTable();
dtn = GetDataTable();
dtPDF = dtn.Copy();
for (int i = 0; i <= dtn.Rows.Count - 1; i++)
{
ExportToPdf(dtPDF);
}
}
public void ExportToPdf(DataTable myDataTable)
{
Document pdfDoc = new Document(PageSize.A4, 10, 10, 10, 10);
try
{
PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);
pdfDoc.Open();
Chunk c = new Chunk("" + System.Web.HttpContext.Current.Session["CompanyName"] + "", FontFactory.GetFont("Verdana", 11));
Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_CENTER;
p.Add(c);
pdfDoc.Add(p);
string clientLogo = Server.MapPath(".") + "/logo/tpglogo.jpg";
string imageFilePath = Server.MapPath(".") + "/logo/tpglogo.jpg";
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);
//Resize image depend upon your need
jpg.ScaleToFit(80f, 60f);
//Give space before image
jpg.SpacingBefore = 0f;
//Give some space after the image
jpg.SpacingAfter = 1f;
jpg.Alignment = Element.HEADER;
pdfDoc.Add(jpg);
Font font8 = FontFactory.GetFont("ARIAL", 7);
DataTable dt = myDataTable;
if (dt != null)
{
//Craete instance of the pdf table and set the number of column in that table
PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
PdfPCell PdfPCell = null;
for (int rows = 0; rows < dt.Rows.Count; rows++)
{
for (int column = 0; column < dt.Columns.Count; column++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
PdfTable.AddCell(PdfPCell);
}
}
//PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table
pdfDoc.Add(PdfTable); // add pdf table to the document
}
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf");
System.Web.HttpContext.Current.Response.Write(pdfDoc);
Response.Flush();
Response.End();
//HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (DocumentException de)
{
System.Web.HttpContext.Current.Response.Write(de.Message);
}
catch (IOException ioEx)
{
System.Web.HttpContext.Current.Response.Write(ioEx.Message);
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Response.Write(ex.Message);
}
}

Why is part of the image cut out when taking a picture with this code on Blackberry?

When I take a picture on the simulator (Haven't tried a device yet) the result is only less than half of the image and the rest is gray. Does anyone know why?
Thanks
listener = new FileSystemJournalListener()
{
private long _lastUSN;
public void fileJournalChanged()
{
long nextUSN = FileSystemJournal.getNextUSN();
FileSystemJournalEntry entry = FileSystemJournal.getEntry(nextUSN - 1);
nextUSN++;
switch (entry.getEvent()) {
case FileSystemJournalEntry.FILE_ADDED:
try
{
FileConnection fconn = (FileConnection)Connector.open("file://" +entry.getPath());
if(fconn.exists())
{
InputStream input = null;
input = fconn.openInputStream();
byte[] data = new byte[(int) fconn.fileSize() + 1000];
input.read(data);
rawImage = data;
pic = Bitmap.createBitmapFromBytes(data, 0, -1, 1);
if(input != null)
{
input.close();
}
Bitmap[] images = new Bitmap[1];
images[0] = pic;
//labels[1] = "Label for image 2";
// tooltips[1] = "Tooltip for image 2";
// labels[2] = "Label for image 2";
// tooltips[2] = "Tooltip for image 2";
ScrollEntry[] entries = new ScrollEntry[images.length];
entries[0] = new ScrollEntry(images[0], "", "");
PictureScrollField pictureScrollField = new PictureScrollField(175, 131);
pictureScrollField.setData(entries, 0);
pictureScrollField.setHighlightStyle(HighlightStyle.ILLUMINATE_WITH_SHRINK_LENS);
// pictureScrollField.setHighlightBorderColor(Color.BLUE);
pictureScrollField.setBackground(BackgroundFactory.createSolidTransparentBackground(Color.BLACK, 150));
insert(pictureScrollField, 1);
picTaken = true;
EventInjector.KeyEvent inject = new EventInjector.KeyEvent(EventInjector.KeyEvent.KEY_DOWN, Characters.ESCAPE, 0, 50);
inject.post();
inject.post();
}
break;
}
catch (Exception e)
{
// TODO Auto-generated catch block
Dialog.alert(e.toString());
}
//either a picture was taken or a picture was added to the BlackBerry device
case FileSystemJournalEntry.FILE_DELETED:
//a picture was removed from the BlackBerry device;
break;
}
input.read(data) only reads some amount of data, not all of it. If you want to read the whole file, use IOUtilities.streamToBytes(input); instead, like this:
byte[] data = IOUtilities.streamToBytes(input);
byte[] data = new byte[(int) fconn.fileSize() + 1000];
...
pic = Bitmap.createBitmapFromBytes(data, 0, -1, 1);
I think data now contains last wrong 1000 bytes, try changing to:
byte[] data = new byte[(int) fconn.fileSize()];
I faced the same problem. Just use:
synchronized(UiApplication.getEventLock()) {
//your code here
}

Resources