Just started to use POI 3.10 to create a Word document (XWPF).
Most of the things are straight forward, but I don't understand how to add page numbers.
I added the footer, but the text in the footer is the same on every page
I created a page number in the footer on the right in LibreOffice and investigated the XML file (MS Word-Std-Objects are not supported in POI which is used there for page numbers).
This will enable to create more complex footers...
to set the number to other positions set another value for ctjc instead of STJc.RIGHT...
The result is the following:
// create footer
XWPFHeaderFooterPolicy policy = doc.getHeaderFooterPolicy();
CTP ctpFooter = CTP.Factory.newInstance();
XWPFParagraph[] parsFooter;
// add style (s.th.)
CTPPr ctppr = ctpFooter.addNewPPr();
CTString pst = ctppr.addNewPStyle();
pst.setVal("style21");
CTJc ctjc = ctppr.addNewJc();
ctjc.setVal(STJc.RIGHT);
ctppr.addNewRPr();
// Add in word "Page "
CTR ctr = ctpFooter.addNewR();
CTText t = ctr.addNewT();
t.setStringValue("Page ");
t.setSpace(Space.PRESERVE);
// add everything from the footerXXX.xml you need
ctr = ctpFooter.addNewR();
ctr.addNewRPr();
CTFldChar fch = ctr.addNewFldChar();
fch.setFldCharType(STFldCharType.BEGIN);
ctr = ctpFooter.addNewR();
ctr.addNewInstrText().setStringValue(" PAGE ");
ctpFooter.addNewR().addNewFldChar().setFldCharType(STFldCharType.SEPARATE);
ctpFooter.addNewR().addNewT().setStringValue("1");
ctpFooter.addNewR().addNewFldChar().setFldCharType(STFldCharType.END);
XWPFParagraph footerParagraph = new XWPFParagraph(ctpFooter, doc);
parsFooter = new XWPFParagraph[1];
parsFooter[0] = footerParagraph;
policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, parsFooter);
org.apache.poi:poi:3.17, org.apache.poi:poi-ooxml:3.17, org.apache.poi:ooxml-schemas:1.3
CTP ctp = CTP.Factory.newInstance();
CTText txt = ctp.addNewR().addNewT();
txt.setStringValue("Page ");
txt.setSpace(SpaceAttribute.Space.PRESERVE);
CTR run = ctp.addNewR();
run.addNewFldChar().setFldCharType(STFldCharType.BEGIN);
run.addNewInstrText().setStringValue(" PAGE ");
run.addNewFldChar().setFldCharType(STFldCharType.END);
txt = ctp.addNewR().addNewT();
txt.setStringValue(" of ");
txt.setSpace(SpaceAttribute.Space.PRESERVE);
run = ctp.addNewR();
run.addNewFldChar().setFldCharType(STFldCharType.BEGIN);
run.addNewInstrText().setStringValue(" NUMPAGES ");
run.addNewFldChar().setFldCharType(STFldCharType.END);
XWPFParagraph par = new XWPFParagraph(ctp, document);
par.setAlignment(ParagraphAlignment.CENTER);
XWPFHeaderFooterPolicy policy = document.getHeaderFooterPolicy();
if (policy == null)
policy = document.createHeaderFooterPolicy();
policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, new XWPFParagraph[] { par });
And you got Page 1 of 9 in footer.
CTP ctp = CTP.Factory.newInstance();
//this add page number incremental
ctp.addNewR().addNewPgNum();
XWPFParagraph codePara = new XWPFParagraph(ctp, document);
XWPFParagraph[] paragraphs = new XWPFParagraph[1];
paragraphs[0] = codePara;
//position of number
codePara.setAlignment(ParagraphAlignment.CENTER);
CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
try {
XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy(document, sectPr);
headerFooterPolicy.createFooter(STHdrFtr.DEFAULT, paragraphs);
} catch (IOException | XmlException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Hope this helps.
XWPFParagraph p1 = doc.createParagraph();
XWPFRun r1 = p1.createRun();
r1.setText("Page ");
r1.getCTR().addNewPgNum();
r1.setText(" of 9");
p1.setAlignment(ParagraphAlignment.RIGHT);
Related
I am trying to create a a paragraph with continuous text .I am not being able to add a footnote in between
in between a continuous paragraph, either it got added at the last or i need to create another paragraph for the next sentences.
1. Below is the snippet for the code attached for the explaination :
public class WordBuilder1 {
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("The table:");
createFootNote(document);
createParagraph(document, "This is the second sentence", 12, ParagraphAlignment.LEFT, false, UnderlinePatterns.NONE);
CTSectPr sectPr = document.getDocument().getBody().getSectPr();
if (sectPr == null) sectPr = document.getDocument().getBody().addNewSectPr();
CTPageSz pageSz = sectPr.addNewPgSz();
pageSz.setOrient(STPageOrientation.PORTRAIT);
pageSz.setW(BigInteger.valueOf(11900)); //12240 Twips = 12240/20 = 612 pt = 612/72 = 8.5"
pageSz.setH(BigInteger.valueOf(16840)); //15840 Twips = 15840/20 = 792 pt = 792/72 = 11"
FileOutputStream out = new FileOutputStream("C:\\Users\\mishrne\\example.docx");
document.write(out);
out.close();
}
private static void createFootNote(XWPFDocument document) {
XWPFRun run = document.createParagraph().createRun();
run.setText("This is a footnote first line");
run.setFontFamily(TIMES_NEW_ROMAN);
run.setFontSize(12);
if (document.getFootnotes().isEmpty()) {
document.createFootnotes();
}
prepareFootNotes(document, FOOTNOTE_TEXT);
// if styles dont already exist then create them
if (document.getStyles() == null) {
document.createStyles();
}
prepareFooterStyle(document);
}
//create paragraph
private static void createParagraph(XWPFDocument document, String text, int fontSize, ParagraphAlignment paragraphAlignment, boolean isBold, UnderlinePatterns single) {
XWPFParagraph paragraph = document.createParagraph();
if (paragraphAlignment != null) {
paragraph.setAlignment(paragraphAlignment);
}
XWPFRun run = paragraph.createRun();
run.setText(text);
run.setFontFamily("Times New Roman");
run.setFontSize(fontSize);
run.setUnderline(single);
run.setBold(isBold);
}
private static void prepareFootNotes(XWPFDocument document, String footnotesText) {
// add footnote
CTFtnEdn ctfInstance = CTFtnEdn.Factory.newInstance();
BigInteger id = new BigInteger("1");
ctfInstance.setId(id);
CTP ctp = ctfInstance.addNewP();
ctp.addNewPPr().addNewPStyle().setVal("FootnoteText");
CTR ctr = ctp.addNewR();
ctr.addNewRPr().addNewRStyle().setVal("FootnoteReference");
ctr.addNewFootnoteRef();
CTText cttext = ctp.addNewR().addNewT();
cttext.setStringValue(footnotesText);
cttext.setSpace(SpaceAttribute.Space.PRESERVE);
// add footnote to document
document.addFootnote(ctfInstance);
ctr = document.getParagraphArray(1).getCTP().addNewR();
ctr.addNewRPr().addNewRStyle().setVal("FootnoteReference");
ctr.addNewFootnoteReference().setId(id);
}
private static void prepareFooterStyle(XWPFDocument document) {
CTStyle style = CTStyle.Factory.newInstance();
style.setStyleId("FootnoteReference");
style.setType(STStyleType.CHARACTER);
style.addNewName().setVal("footnote reference");
style.addNewBasedOn().setVal("DefaultParagraphFont");
style.addNewUiPriority().setVal(new BigInteger("99"));
style.addNewSemiHidden();
style.addNewUnhideWhenUsed();
style.addNewRPr().addNewVertAlign().setVal(STVerticalAlignRun.SUPERSCRIPT);
// add style
document.getStyles().addStyle(new XWPFStyle(style));
style.setType(STStyleType.PARAGRAPH);
CTDecimalNumber indentNumber = CTDecimalNumber.Factory.newInstance();
indentNumber.setVal(BigInteger.valueOf(100));
style.setStyleId("FootnoteText");
style.addNewName().setVal("footnote text");
style.addNewBasedOn().setVal("Normal");
style.addNewLink().setVal("FootnoteTextChar");
style.addNewUiPriority().setVal(new BigInteger("99"));
style.addNewSemiHidden();
style.addNewUnhideWhenUsed();
CTRPr rpr = style.addNewRPr();
rpr.addNewSz().setVal(new BigInteger("20"));
rpr.addNewSzCs().setVal(new BigInteger("20"));
// add style
document.getStyles().addStyle(new XWPFStyle(style));
}
private static void setHeaderRowforSingleCell(XWPFTableCell cell, String text) {
XWPFParagraph tempParagraph = cell.getParagraphs().get(0);
tempParagraph.setIndentationLeft(100);
tempParagraph.setIndentationRight(100);
tempParagraph.setAlignment(ParagraphAlignment.RIGHT);
tempParagraph.setSpacingAfter(50);
XWPFRun tempRun = tempParagraph.createRun();
tempRun.setFontSize(10);
tempRun.setText(text);
cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
}}
In Word creating a footnote needs two parts. First creating the footnote on document level. Second attaching the footnote reference to a text run.
The following approach provides a method BigInteger createFootnote(XWPFDocument document, String footnoteText) for creating a footnote on document level. It returns the footnote identifier to be usable as footnote reference then. The attaching the footnote reference to an text run can be done then using run.getCTR().addNewFootnoteReference().setId(footnoteId); where run is a XWPFRun.
If the need is formatting the footnote references, as superscript for example, then Word itself creates a special character style for this. This also needs two parts. First create the style on document level:
XWPFStyles styles = document.createStyles();
XWPFStyle style = new XWPFStyle(CTStyle.Factory.newInstance(), styles);
style.getCTStyle().setType(STStyleType.CHARACTER);
style.getCTStyle().setStyleId("FootnoteReference");
style.getCTStyle().addNewRPr().addNewVertAlign().setVal(STVerticalAlignRun.SUPERSCRIPT);
styles.addStyle(style);
Then apply this style to the text runs:
run.getCTR().addNewRPr().addNewRStyle().setVal("FootnoteReference");
For this, the footnote references must be in their own text runs.
Complete example:
import java.io.FileOutputStream;
import java.math.BigInteger;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTFtnEdn;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyle;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STStyleType;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalAlignRun;
public class CreateWordFootnotes {
static BigInteger createFootnote(XWPFDocument document, String footnoteText) {
XWPFFootnotes footnotes = document.createFootnotes();
CTFtnEdn ctFtnEdn = CTFtnEdn.Factory.newInstance();
BigInteger footnoteId = BigInteger.valueOf(footnotes.getFootnotesList().size());
ctFtnEdn.setId(footnoteId);
XWPFFootnote footnote = footnotes.addFootnote(ctFtnEdn);
XWPFParagraph paragraph = footnote.addNewParagraph(CTP.Factory.newInstance());
XWPFRun run=paragraph.createRun();
run.getCTR().addNewFootnoteRef();
run.getCTR().addNewRPr().addNewRStyle().setVal("FootnoteReference");
run = paragraph.createRun();
run.setText(footnoteText);
return footnoteId;
}
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
XWPFStyles styles = document.createStyles();
XWPFStyle style = new XWPFStyle(CTStyle.Factory.newInstance(), styles);
style.getCTStyle().setType(STStyleType.CHARACTER);
style.getCTStyle().setStyleId("FootnoteReference");
style.getCTStyle().addNewRPr().addNewVertAlign().setVal(STVerticalAlignRun.SUPERSCRIPT);
styles.addStyle(style);
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("The text");
paragraph = document.createParagraph();
run = paragraph.createRun();
run.setText("This is the text run having the first footnote");
String footnoteText = "The content of the first footnote.";
BigInteger footnoteId = createFootnote(document, footnoteText);
run = paragraph.createRun();
run.getCTR().addNewRPr().addNewRStyle().setVal("FootnoteReference");
run.getCTR().addNewFootnoteReference().setId(footnoteId);
run = paragraph.createRun();
run.setText(" further text comes here and a second footnote");
footnoteText = "The content of the second footnote.";
footnoteId = createFootnote(document, footnoteText);
run = paragraph.createRun();
run.getCTR().addNewRPr().addNewRStyle().setVal("FootnoteReference");
run.getCTR().addNewFootnoteReference().setId(footnoteId);
run = paragraph.createRun();
run.setText(" and now the paragraph ends here.");
paragraph = document.createParagraph();
FileOutputStream out = new FileOutputStream("CreateWordFootnotes.docx");
document.write(out);
out.close();
document.close();
}
}
The code needs the full jar of all of the schemas ooxml-schemas or poi-ooxml-full as mentioned in https://poi.apache.org/help/faq.html#faq-N10025.
Using apache poi 5.x it must be
...
//import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalAlignRun;
import org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STVerticalAlignRun;
...
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.
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
I'm trying to build a custom webpart for displaying upcoming birthdays.
This code works but I need to retrieve the Birthday to filter my results.
I tried using SPS-Birthday but then I get an exception
public static void BirthDay()
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Site.ID))
{
StringBuilder queryText = new StringBuilder();
queryText.Append("SELECT PreferredName, AccountName, ??SPS-BIRTHDAY??");
queryText.Append("FROM SCOPE() ");
queryText.Append("WHERE \"scope\" = 'People' ");
using (FullTextSqlQuery query = new FullTextSqlQuery(site))
{
query.QueryText = queryText.ToString();
query.RankingModelId = "D9BFB1A1-9036-4627-83B2-BBD9983AC8A1";
query.KeywordInclusion = KeywordInclusion.AnyKeyword;
query.ResultTypes = ResultType.RelevantResults;
query.RowLimit = 5000;
ResultTableCollection results = new ResultTableCollection();
try
{
results = query.Execute();
if (results.Count == 0)
throw new ArgumentException("// No results");
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex.InnerException);
}
ResultTable relevantResults = results[ResultType.RelevantResults];
resultDataTable = new DataTable();
resultDataTable.Load(relevantResults, LoadOption.OverwriteChanges);
count = resultDataTable.Rows.Count;
}
}
});
Try going into Central Admin and making sure that the Birthday field can be "Used in Scopes". Go to Central Admin->Manage Search Service application->Metadata Properties...then look for and select that Birthday property under Managed Properties...then click "Use this field in scopes"
the error i get is
The security validation for this page is invalid. Click Back in your Web browser, refresh the page and try the operation again.
i am using moss 2007
protected void btnSubmit_Click(Object sender, EventArgs e)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPUtility.ValidateFormDigest();
using (SPSite mySite = new SPSite(_sLibUrl))
{
TextBox txtFirstName = (TextBox)usercontrol.FindControl("txtFirstName");
TextBox txtLastName = (TextBox)usercontrol.FindControl("txtLastName");
TextBox txtPhone = (TextBox)usercontrol.FindControl("txtPhone");
TextBox txtEmail = (TextBox)usercontrol.FindControl("txtEmail");
TextBox txtSubject = (TextBox)usercontrol.FindControl("txtSubject");
TextBox txtContant = (TextBox)usercontrol.FindControl("txtContant");
mySite.AllowUnsafeUpdates = true;
SPListItemCollection listItems = mySite.AllWebs[WebName].Lists[_sLibName].Items;
SPListItem item = listItems.Add();
item["FirstName"] = txtFirstName.Text;
item["LastName"] = txtLastName.Text;
item["Phone"] = txtPhone.Text;
item["Email"] = txtEmail.Text;
item["Subject"] = txtSubject.Text;
item["Contant"] = txtContant.Text;
item.Update();
mySite.AllowUnsafeUpdates = false;
mySite.AllWebs[WebName].Lists[_sLibName].Update();
txtFirstName.Text = string.Empty;
txtLastName.Text = string.Empty;
txtPhone.Text = string.Empty;
txtEmail.Text = string.Empty;
txtSubject.Text = string.Empty;
txtContant.Text = string.Empty;
}
Label lblMessage = (Label)usercontrol.FindControl("lblMessage");
// lblMessage.Text = "טופס נשלח בהצלחה";
});
}
catch (Exception ex)
{
Label lbl = (Label)usercontrol.FindControl("lblMessage");
lbl.Text = ex.Message;
}
}
Try putting mySite.AllowUnsafeUpdates = false; after mySite.AllWebs[WebName].Lists[_sLibName].Update();
i found the solution what i need to do is to remove the
mySite.AllowUnsafeUpdates = true;
and
mySite.AllowUnsafeUpdates = false;
and it works
I work with this solution always
using (var site = new SPSite(SPContext.Current.Site.ID))
using (var web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//add, update and etc. programatically crud operations with lists
web.AllowUnsafeUpdates = false;
}