Apache POI Docx - insert img in existing document Header - apache-poi

I need to insert an img in the header of an existing docx.
My code:
XWPFDocument docx = new XWPFDocument(new FileInputStream("test.docx"));
XWPFHeaderFooterPolicy headerPolicy = docx.getHeaderFooterPolicy();
XWPFHeader header = headerFooterPolicy.getDefaultHeader();
XWPFParagraph parNew = header.createParagraph();
parNew.setAlignment(ParagraphAlignment.LEFT);
XWPFRun run = parNew.createRun();
String pathImg="FILE/logo/logo_top.jpg";
InputStream in = new FileInputStream(pathImg);
XWPFPicture picture = run.addPicture(
in,
XWPFDocument.PICTURE_TYPE_JPEG,
"logo",
Units.toEMU(150), Units.toEMU(50));
in.close();
String blipID = "";
for(XWPFPictureData picturedata : header.getAllPackagePictures()) {
blipID = header.getRelationId(picturedata);
System.out.println("blipID: " + blipID);
}
picture.getCTPicture().getBlipFill().getBlip().setEmbed(blipID);
FileOutputStream fos = new FileOutputStream("test_headerImg.docx");
docx.write(fos);
When i open the docx modified i get an "Error in opening file" error.
Thanks for any help.

Related

ExceptionInInitializerError on Itext 7

I tried to make PDF with itext 7.2.1, this is my code:
try{
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Kegiatan/" + eventName + ".pdf";
File file = new File(path);
file.mkdirs();
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document document = new Document(pdfDoc, new PageSize(612, 936).rotate());
document.setMargins(0,0,0,0);
//Title
Paragraph paragraph = new Paragraph();
paragraph.add(new Text(eventName).setFontSize(14).setTextAlignment(TextAlignment.CENTER).setBold());
document.add(paragraph);
document.close();
}
catch (IOException e) {
e.printStackTrace();
}
I got this error message, pointing at document.close()
java.lang.ExceptionInInitializerError
How i can fix this?

Not able to get excel file from web api dot net core 2.1 using epplus excel package

I'm trying to generate an excel file / stream in my web api and return it in a HttpResponseMessage to serve it to the client in Angular 5 as a download.
The generation succeeds and an xlsx file is generated and saved on the server, but when I return it in the Content of my httpResponseMessage, my browser shows just some json instead of the whole excel file.
{"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},"content":{"headers":[{"key":"Content-Disposition","value":["attachment; filename=636742856488421817.xlsx"]},{"key":"Content-Type","value":["application/ms-excel"]},{"key":"Content-Length","value":["22780"]}]},"statusCode":200,"reasonPhrase":"OK","headers":[],"requestMessage":null,"isSuccessStatusCode":true}
This is how I create the excel file and returns it:
var dataBytes = File.ReadAllBytes(fileName);
var dataStream = new MemoryStream(dataBytes);
HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
httpResponseMessage.Content = new StreamContent(dataStream);
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = fileName;
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/ms-excel");
httpResponseMessage.Content.Headers.ContentLength = dataStream.Length;
I solved this:
Here is what I did
Helper class which creates the excel package and converts it to a Stream
var fileName = DateTime.Now.Ticks + ".xlsx";
FileInfo file = new FileInfo(fileName);
FileInfo templateFile = new FileInfo(#"Templates/ReportTemplate.xlsx");
ExcelPackage package = new ExcelPackage(file, templateFile);
ExcelWorksheet worksheet = package.Workbook.Worksheets.FirstOrDefault();
... filling rows and cells goed here ...
var dataBytes = package.GetAsByteArray();
Stream dataStream = new MemoryStream(dataBytes);
dataStream.Seek(0, SeekOrigin.Begin);
return dataStream;
In the controller I return the file to the Angular client like this:
var stream = _helperClass.GenerateReport(exportDate, exportTitle);
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", $"Report-{DateTime.Now.ToShortDateString()}.xlsx");
In the Angular component I do this after I receive the response:
var blob = new Blob([res], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
var blobURL = window.URL.createObjectURL(blob);
var anchor = document.createElement("a");
anchor.download = `Report-${new Date().toISOString()}.xlsx`;
anchor.href = blobURL;
anchor.click();
Try this following code:
For conroller:
[Route("DownLoadExcel")]
public IActionResult DownLoadExcel()
{
var pack = new ExcelPackage();
ExcelWorksheet worksheet = pack.Workbook.Worksheets.Add("sample");
//First add the headers
worksheet.Cells[1, 1].Value = "ID";
worksheet.Cells[1, 2].Value = "Name";
//Add values
worksheet.Cells["A2"].Value = 1000;
worksheet.Cells["B2"].Value = "Jon";
return File(pack.GetAsByteArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Sample.xlsx");
}
For client side:
window.open("../.../DownLoadExcel");

Exporting from GridView to Excel is not show Persian correctly

Bind the GridView by SqlDataSource and I wrote below code to export from GridView to Excel:
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
gvReportPrint.GridLines = GridLines.Both;
gvReportPrint.Font.Name = "'BYekan'";
foreach (GridViewRow row in gvReportPrint.Rows)
{
row.Cells[2].Attributes.Add("class", "textmode");
}
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
gvReportPrint.HeaderStyle.Font.Bold = true;
Response.Write(style);
gvReportPrint.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.End();
During Export From GridView to Excel, unicode characters don't show correctly,
they are shown like this:
--> Click this link to show the problem <--
It seems that you are using asp:GridView,I had the same issue and using GridView class solved it like below :
public void ToExcel(DataTable dt, string reportName)
{
if (dt.Rows.Count > 0)
{
string filename = string.Format("{0}.xls", reportName);
GridView gv = new GridView();
gv.DataSource = dt;
gv.HeaderStyle.BackColor = System.Drawing.Color.FromArgb(0, 119, 179);
gv.HeaderStyle.ForeColor = System.Drawing.Color.FromArgb(250, 250, 250);
gv.AlternatingRowStyle.BackColor = System.Drawing.Color.FromArgb(191, 191, 191);
gv.Font.Name = "Tahoma";
gv.Font.Size = 10;
gv.DataBind();
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode;
HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
gv.RenderControl(hw);
HttpContext.Current.Response.Output.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
and dt should be your data source for gridview.
Also please take a look at ASP.NET Excel export encoding problem

Converting from HWPFDocument to XWPFDocument or vice versa

I have a Word document, where I have to replace text and save this document in Oracle database, in PDF format. Have someone any idea how to resolve this?
String inputFilename = "/root/GeneratorUmow/web/WEB-INF/umowy/kkb/wniosekozaciag.docx";
try(InputStream is = new FileInputStream(inputFilename)) {
dbd = new DokumentyBlobDAO();
db.setNazwaPliku("Wniosek_o_zaciagniecie.pdf");
db.setTypDokuemntu(876990);
if(du.getTypKlienta() == S_ID_Lead_Partner_Typ_Klienta_KKB) {
POIFSFileSystem fs = null;
fs = new POIFSFileSystem(is);
HWPFDocument doc = new HWPFDocument(fs); //funkcja zamyka inputstream
Range range = doc.getRange();
range.replaceText("my&&nazwa&&firmy", "KAKAOWY SZATAN");
//konwersja na pdf
FileOutputStream fos = new FileOutputStream(pathToDirectory + File.separator + folderName+File.separator + "wniosekzaciagniecie.docx");
doc.write(fos);
String inputChangeFile = pathToDirectory+ File.separator +folderName+File.separator+"wniosekzaciagniecie.docx";
InputStream inputstream = new FileInputStream(inputFilename);
length = inputChangeFile.length();
System.out.println("dlugosc lancucha " + length);
XWPFDocument document = new XWPFDocument(inputstream);
System.out.println("message3");
PdfOptions options = PdfOptions.create();
PdfOptions options = PdfOptions.create().fontEncoding("windows-1250");
System.out.println("message4");
OutputStream out = new FileOutputStream(new File(pathToDirectory+ File.separator +folderName+File.separator+"kakaowyszal.pdf"));
PdfConverter.getInstance().convert(document, out, options);
System.out.println("message5");
}
}
catch( Exception ex){
System.out.println("err" + ex);
return -1;
}

Program terminates when reading data from excel in selenium web driver

I am matching console output value with excel data. And in excel try to putting "TRUE" or "FALSE" if match found. My program is given below :
WebDriver driver = new FirefoxDriver();
driver.get("http://en.wikipedia.org/wiki/Software_testing");
String title = driver.getTitle();
System.out.println(title);
FileInputStream input = new FileInputStream("D:\\book.xls");
FileOutputStream webdata = new FileOutputStream ("D:\\book.xls");
int count=0;
HSSFWorkbook wb = new HSSFWorkbook(input);
HSSFSheet sh = wb.getSheet("sheet1");
HSSFRow row = sh.getRow(count);
String data = row.getCell(1).toString();
System.out.println(data);
if(title==data)
{
row.createCell(10).setCellValue("TRUE");
wb.write(webdata);
}
else
{
row.createCell(10).setCellValue("FALSE");
wb.write(webdata);
}
wb.close();
input.close();
driver.close();
When program reach here : HSSFWorkbook wb = new HSSFWorkbook(input); It terminates. I have debug it but not getting solution. can anyone help please?
I am getting below error in console :
Exception in thread "main" java.io.IOException: Unable to read entire header; 0 bytes read; expected 512 bytes
at org.apache.poi.poifs.storage.HeaderBlock.alertShortRead(HeaderBlock.java:227)
at org.apache.poi.poifs.storage.HeaderBlock.readFirst512(HeaderBlock.java:208)
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:104)
at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:128)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:361)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:342)
at mhover.main(mhover.java:52)
Issue it solved now. Problem was like :
FileInputStream input = new FileInputStream("D:\\book.xls");
FileOutputStream webdata = new FileOutputStream ("D:\\book.xls");
Above code was overwriting my excel file data and was making excel blank. So I moved code : FileOutputStream webdata = new FileOutputStream ("D:\book.xls"); once data reading process complete. so its working now.
New & Working code :
//CODE TO REMOVE UNNECESSARY WARNING
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Jdk14Logger");
//CALL FIREFOX DRIVER TO OPEN IT
WebDriver driver = new FirefoxDriver();
driver.get("http://en.wikipedia.org/wiki/Software_testing");
String title = driver.getTitle();
System.out.println(title);
FileInputStream input = new FileInputStream("D:\\sel.xls");
int count=0;
HSSFWorkbook wb = new HSSFWorkbook(input);
HSSFSheet sh = wb.getSheet("sheet1");
HSSFRow row = sh.getRow(count);
String data = row.getCell(1).toString();
System.out.println(data);
FileOutputStream webdata = new FileOutputStream ("D:\\sel.xls");
if(title.equals(data))
{
row.createCell(10).setCellValue("TRUE");
wb.write(webdata);
}
else
{
row.createCell(11).setCellValue("FALSE");
wb.write(webdata);
}
driver.close();
wb.close();
input.close();
}
}

Resources