iText PDF Exporter UTF-8 Character Encoding Error - utf-8

I'm facing with character encoding issue while exporting PDF with using iText PDF Library despite I set exporter's CHARACTER_ENCODING property to UTF-8 as I added below :
Class clazz = Class.forName(User.class);
Document document = new Document();
PdfWriter.getInstance(document, baos);
document.open();
addMetaData(document);
addDate(document);
addTitlePage(document, className);
addEmptyLineToDocument(document, 2);
addContent(document, className, clazz);
addEmptyLineToDocument(document, 2);
addSignature(document);
return document;
Here's the addContent method sample:
private static FontFamily fontFamily = FontFamily.TIMES_ROMAN;
Font fontNormal10 = new Font(fontFamily, 10, Font.NORMAL);
Paragraph paragraph = new Paragraph();
Chunk chunk = new Chunk("Here is the list of " + className, fontNormal10);
paragraph.add(chunk);
// continues
Then I write the document with ServletOutputStream :
// **document** => which I created and returned above
document.close();
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
response.setHeader("Content-Disposition", "attachment; filename=" + outputFileName);
response.setContentType("application/pdf; charset=UTF-8");
response.setContentLength(baos.size());
ServletOutputStream outputStream = response.getOutputStream();
baos.writeTo(outputStream);
outputStream.flush();
outputStream.close();
I also added JVM parameter "file.encoding=UTF-8" too..
Set response content type with "charset=UTF-8;" property..
Any ideas? Thanks in advance..

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.

Velocity pdf Image not displayed

I generated pdf file using velocity templates but i am not able to put images in my pdf.
I've try using external and internal images but the picture still not displaying.
I also have tried this tutorial but still not showing images in generated pdf.
`File f = new File("D:\\uploadfile\\assets\\test.png");
FileInputStream fin = new FileInputStream(f);
byte imagebytearray[] = new byte[(int)f.length()];
fin.read(imagebytearray);
String imagetobase64 = Base64.encodeBase64String(imagebytearray);
fin.close();
logger.info("data: "+imagetobase64);
context.put("image", imagetobase64);
/* now render the template into a StringWriter */
StringWriter writer = new StringWriter();
t.merge(context, writer);
/* show the World */
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos = generatePdf(writer.toString());
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_PDF);
header.set(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=" + fileName.replace(" ", "_"));
header.setContentLength(baos.toByteArray().length);
return new HttpEntity<byte[]>(baos.toByteArray(), header);`
On vm template i try, but the images still not diplayed
<img src="data:image/png;base64,$image" border="0" width="50" height="50"/>
<img src="https://www.jamasoftware.com/media/gravatar/jama-avatar.png"/>
Any help or sugestion?
Thanks

How to download File from pdf which has its filepath in .NET Core API?

I am generating a PDF from HTML and I had some file which was added in PDF in this format:
BUT those link unable to download - I get an "Unauthorized" error...
My code:
if (DocumentAfter != null)
{
string documentAElement = "";
foreach (var item in DocumentAfter)
{
var path2 = FromEmaillID + item.FileName;
// var filePath2 = Path.Combine(Environment.WebRootPath, #"document", item.FileName);
documentAElement += "" + item.FileName + "<br />";
}
emailKeyValues.Add(EmailConstants.AfterDocuments, documentAElement);
}
In this code there are more than one file I am adding in an anchor tag and it will then assign to html with EmailConstants.AfterDocuments
And my pdf download code is
Byte[] bytes;
StringBuilder sb1 = new StringBuilder();
sb1.Append(emailMessage.Content);//Pass html string here
StringReader sr = new StringReader(sb1.ToString());
Document pdfDoc = new Document(PageSize.A4, 25, 25, 25, 25);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
using (MemoryStream memoryStream = new MemoryStream())
{
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
pdfDoc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
//htmlparser.Parse(sr);
pdfDoc.Close();
bytes = memoryStream.ToArray();
memoryStream.Close();
//var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "yogTest.pdf");
System.IO.File.WriteAllBytes(filepath1, bytes);
}
This code is working properly as PDF is shown, but only the file which I am adding for downloading is not working?

Convert HTTPResponse to image

For one of the implementation, from Java code I am hitting labelary Rest service to convert ZPL formatted code to Image.
I am able to successfully fetch the response. But I am not able to convert the HttpResponse to image file.
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost "http://api.labelary.com/v1/printers/8dpmm/labels/4x6/0/");
byte[] byteArray = Base64.decodeBase64(base64Val.getBytes());
String decodedString = new String(byteArray);
StringEntity requestEntity;
try {
requestEntity = new StringEntity(decodedString);
requestEntity.setContentType("application/x-www-form-urlencoded");
post.setEntity(requestEntity);
HttpResponse response = client.execute(post);
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
#Need suggestions to convert BufferReader to Image
}
Post referring the suggested answer, code looks like:
HttpResponse response = client.execute(post);
InputStream inStream = response.getEntity().getContent();
String dataString = convertStreamToString(inStream);
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(dataString);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
File outputfile = new File("myImage.png");
ImageIO.write(image, "png", outputfile);
use this byte to image converter. past value in datastring and check whether you get the image.

valence desire 2 learn profile image upload error 404

I'm trying to upload an image profile using the api but I'm getting a Unknown: NOT_FOUND 404 error. the call I am using is POST /d2l/api/lp/1.3/profile/(profileId)/image, I am passing the content type, length and filename (profileImage). I'm passing the image as a dataStream. I've reduced the size of the image as well. Any ideas?
public static void UploadFilesToRemoteUrl(string file, string logpath, NameValueCollection nvc, ID2LUserContext userContext, string accion)
{
var uri = userContext.CreateAuthenticatedUri(accion, "POST");
string boundary = "bde472ff1f1a46539e54e655857c27c1";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.ContentType = "multipart/form-data; boundary=" +
boundary;
request.Headers.Add("Accept-Encoding", "gzip, deflate, compress");
request.Method = "POST";
request.KeepAlive = true;
request.Proxy.Credentials = new NetworkCredential(Constantes.UsuarioProxy, Constantes.PasswordProxy, Constantes.DominioProxy);
Stream memStream = new System.IO.MemoryStream();
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
boundary + "\r\n");
string formdataTemplate = "\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"profileImage\"; filename=\"profileImage.png\" \r\nContent-Type: image/png\r\n";
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formdataTemplate);
memStream.Write(formitembytes, 0, formitembytes.Length);
// Read image File *************************************************************
FileStream fileStream = new FileStream(file, FileMode.Open,FileAccess.Read);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
memStream.Write(buffer, 0, bytesRead);
}
fileStream.Close();
//*****************************************************************************
//*********** End Read image file *********************************************
memStream.Write(boundarybytes, 0, boundarybytes.Length);
request.ContentLength = memStream.Length;
Stream requestStream = request.GetRequestStream();
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseValence = reader.ReadToEnd();
}
It seems most likely that the 404 is coming either from
The API route you're providing (and the back-end service cannot match your API route to a handler method): this could be because of an incorrect profileId value, or a mis-typed route, or an incorrect API version number in the route, and so forth.
That for some reason the back-end service is accepting your profile image data but then unable to assign it to the user's profile.
Here's a capture of some request/response details of what an uploaded profile image packet looks like. When uploading a profile image to "my profile", I use an HTTP header that gets built from these values:
{'Content-Length': '75143',
'User-Agent': 'python-requests/2.2.1 CPython/3.3.3 Darwin/12.5.0',
'Content-Type': 'multipart/form-data; boundary=bde472ff1f1a46539e54e655857c27c1',
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate, compress'}
Note that this is a multipart/form-data content body, with a boundary marker around a single body part. The body content for the request looks like this:
--bde472ff1f1a46539e54e655857c27c1
Content-Disposition: form-data; name="profileImage"; filename="profile_img-225x225.png"
[actual PNG bytes here]
--bde472ff1f1a46539e54e655857c27c1--
The name property in the Content-Disposition header must be profileImage, and the filename property should be named after the local filename you're using to provide the content (so, as far as the back-end service is concerned, it's value is not particularly relevant).
Finally, there are particular role permissions at play that permit a user to edit someone else's profile image, so you should ensure that your calling user context for the API call has permission to edit someone else's image.
Fixed. This code works correctly:
public static void UploadFilesToRemoteUrl(byte[] profileImage, ID2LUserContext userContext, string accion)
{
//Reference:
//action = "/d2l/api/lp/1.3/profile/" + profileIdentifier + "/image";
//profileImage = the profileImage of user read from disk:
/*
FileStream fileStream = new FileStream(pictureLocalPath, FileMode.Open, FileAccess.Read);
Byte[] img = new Byte[fileStream.Length];
fileStream.Read(img, 0, Convert.ToInt32(img.Length));
fileStream.Close();
*/
var uri = userContext.CreateAuthenticatedUri(accion, "POST");
string boundary = "bde472ff1f1a46539e54e655857c27c1";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.ContentType = "multipart/form-data; boundary=" +
boundary;
request.Headers.Add("Accept-Encoding", "gzip, deflate, compress");
request.Method = "POST";
request.KeepAlive = true;
request.Proxy.Credentials = new NetworkCredential(Constantes.UsuarioProxy, Constantes.PasswordProxy, Constantes.DominioProxy);
Stream memStream = new System.IO.MemoryStream();
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
boundary + "\r\n");
string formdataTemplate = "\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"profileImage\"; filename=\"profileImage.jpg\"\r\nContent-Type: image/jpeg;\r\n\r\n";
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formdataTemplate);
memStream.Write(formitembytes, 0, formitembytes.Length);
//escribo el array de byte de la imagen
memStream.Write(profileImage, 0, profileImage.Length);
byte[] boundaryClose = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--");
memStream.Write(boundaryClose, 0, boundarybytes.Length);
StreamReader readerReq = new StreamReader(memStream);
string stringReq = readerReq.ReadToEnd();
request.ContentLength = memStream.Length;
Stream requestStream = request.GetRequestStream();
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseValence = reader.ReadToEnd();
response.Close();
}
}

Resources