static void Main(string[] args) { XWPFDocument doc = new XWPFDocument(); XWPFParagraph para= doc.CreateParagraph(); XWPFRun r0 = para.CreateRun(); r0.SetText("Title1"); para.BorderTop = Borders.THICK; para.FillBackgroundColor = "EEEEEE"; para.FillPattern = NPOI.OpenXmlFormats.Wordprocessing.ST_Shd.diagStripe; XWPFTable table = doc.CreateTable(3, 3); table.GetRow(1).GetCell(1).SetText("EXAMPLE OF TABLE"); XWPFTableCell c1 = table.GetRow(0).GetCell(0); XWPFParagraph p1 = c1.AddParagraph(); //don't use doc.CreateParagraph XWPFRun r1 = p1.CreateRun(); r1.SetText("The quick brown fox"); r1.SetBold(true); r1.FontFamily = "Courier"; r1.SetUnderline(UnderlinePatterns.DotDotDash); r1.SetTextPosition(100); c1.SetColor("FF0000"); table.GetRow(2).GetCell(2).SetText("only text"); FileStream out1 = new FileStream("simpleTable.docx", FileMode.Create); doc.Write(out1); out1.Close(); }
static void Main(string[] args) { XWPFDocument doc = new XWPFDocument(new FileStream("data/Extract Images from Word Document.doc",FileMode.Open)); IList<XWPFPictureData> pics = doc.AllPictures; foreach (XWPFPictureData pic in pics) { FileStream outputStream = new FileStream("data/NPOI_" + pic.FileName,FileMode.OpenOrCreate); byte[] picData= pic.Data; outputStream.Write(picData, 0, picData.Length); outputStream.Close(); } }
public void LoadFile(String path) { using(var file = new FileStream(path, FileMode.Open, FileAccess.Read)) { _document = new XWPFDocument(file); } }
public void TestCreateRow() { XWPFDocument doc = new XWPFDocument(); CT_Tbl table = new CT_Tbl(); CT_Row r1 = table.AddNewTr(); r1.AddNewTc().AddNewP(); r1.AddNewTc().AddNewP(); CT_Row r2 = table.AddNewTr(); r2.AddNewTc().AddNewP(); r2.AddNewTc().AddNewP(); CT_Row r3 = table.AddNewTr(); r3.AddNewTc().AddNewP(); r3.AddNewTc().AddNewP(); XWPFTable xtab = new XWPFTable(table, doc); Assert.AreEqual(3, xtab.GetNumberOfRows()); Assert.IsNotNull(xtab.GetRow(2)); //add a new row xtab.CreateRow(); Assert.AreEqual(4, xtab.GetNumberOfRows()); //check number of cols Assert.AreEqual(2, table.GetTrArray(0).SizeOfTcArray()); //check creation of first row xtab = new XWPFTable(new CT_Tbl(), doc); Assert.AreEqual(1, xtab.GetCTTbl().GetTrArray(0).SizeOfTcArray()); }
static void Main(string[] args) { XWPFDocument wordDocument = new XWPFDocument( new FileStream("data/Convert Word Doc to Other Formats.doc", FileMode.Open)); using (FileStream sw = File.Create("data/Convert Word Doc to Other Formatsblank.docx")) { wordDocument.Write(sw); } }
public XWPFHeader(XWPFDocument doc, CT_HdrFtr hdrFtr) : base(doc, hdrFtr) { /* XmlCursor cursor = headerFooter.NewCursor(); cursor.SelectPath("./*"); while (cursor.ToNextSelection()) { XmlObject o = cursor.Object; if (o is CTP) { XWPFParagraph p = new XWPFParagraph((CTP) o, this); paragraphs.Add(p); } if (o is CTTbl) { XWPFTable t = new XWPFTable((CTTbl) o, this); tables.Add(t); } } cursor.Dispose();*/ foreach (object o in hdrFtr.Items) { if (o is CT_P) { XWPFParagraph p = new XWPFParagraph((CT_P)o, this); paragraphs.Add(p); } if (o is CT_Tbl) { XWPFTable t = new XWPFTable((CT_Tbl)o, this); tables.Add(t); } } }
public void TestSetGetVertAlignment() { // instantiate the following classes so they'll Get picked up by // the XmlBean process and Added to the jar file. they are required // for the following XWPFTableCell methods. CT_Shd ctShd = new CT_Shd(); Assert.IsNotNull(ctShd); CT_VerticalJc ctVjc = new CT_VerticalJc(); Assert.IsNotNull(ctVjc); ST_Shd stShd = ST_Shd.nil; Assert.IsNotNull(stShd); ST_VerticalJc stVjc = ST_VerticalJc.top; Assert.IsNotNull(stVjc); // create a table XWPFDocument doc = new XWPFDocument(); CT_Tbl ctTable = new CT_Tbl(); XWPFTable table = new XWPFTable(ctTable, doc); // table has a single row by default; grab it XWPFTableRow tr = table.GetRow(0); Assert.IsNotNull(tr); // row has a single cell by default; grab it XWPFTableCell cell = tr.GetCell(0); cell.SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.BOTH); XWPFTableCell.XWPFVertAlign al = cell.GetVerticalAlignment(); Assert.AreEqual(XWPFTableCell.XWPFVertAlign.BOTH, al); }
public DataTable FindTable(string filepath) { try { using (FileStream stream = File.OpenRead(filepath)) { XWPFDocument doc = new XWPFDocument(stream); foreach (XWPFTable table in doc.Tables) { if (Row2Cell1Contains(table, @"Run") && Row1Cell1Contains(table, @"General")) { return WordTableToDataTable.GetDataTable(table); } } return null; } } catch (AccessViolationException avex) { throw new AccessViolationException(string.Format("You do not have permission to access the file " + avex.Message)); } catch (System.IO.IOException ioex) { throw new System.IO.IOException(ioex.Message.Replace("\'", "<br />") + "<br /><br />Someone has file open and it is therefore locked."); } }
static void Main(string[] args) { // Create a new document from scratch XWPFDocument doc = new XWPFDocument(); XWPFTable table = doc.CreateTable(3, 3); table.GetRow(1).GetCell(1).SetText("EXAMPLE OF TABLE"); XWPFTableCell c1 = table.GetRow(0).GetCell(0); XWPFParagraph p1 = c1.AddParagraph(); //don't use doc.CreateParagraph XWPFRun r1 = p1.CreateRun(); r1.SetText("This is test table contents"); r1.SetBold(true); r1.FontFamily = "Courier"; r1.SetUnderline(UnderlinePatterns.DotDotDash); r1.SetTextPosition(100); c1.SetColor("FF0000"); table.GetRow(2).GetCell(2).SetText("only text"); FileStream out1 = new FileStream("Format Table in Document.docx", FileMode.Create); doc.Write(out1); out1.Close(); }
public void Bug55802() { String blabla = "Bir, iki, \u00fc\u00e7, d\u00f6rt, be\u015f,\n" + "\nalt\u0131, yedi, sekiz, dokuz, on.\n" + "\nK\u0131rm\u0131z\u0131 don,\n" + "\ngel bizim bah\u00e7eye kon,\n" + "\nsar\u0131 limon"; XWPFDocument doc = new XWPFDocument(); XWPFRun run = doc.CreateParagraph().CreateRun(); foreach (String str in blabla.Split("\n".ToCharArray())) { run.SetText(str); run.AddBreak(); } run.FontFamily = (/*setter*/"Times New Roman"); run.FontSize = (/*setter*/20); Assert.AreEqual(run.FontFamily, "Times New Roman"); Assert.AreEqual(run.GetFontFamily(FontCharRange.CS), "Times New Roman"); Assert.AreEqual(run.GetFontFamily(FontCharRange.EastAsia), "Times New Roman"); Assert.AreEqual(run.GetFontFamily(FontCharRange.HAnsi), "Times New Roman"); run.SetFontFamily("Arial", FontCharRange.HAnsi); Assert.AreEqual(run.GetFontFamily(FontCharRange.HAnsi), "Arial"); }
public void TestWord() { POIXMLDocument doc = new XWPFDocument( POIDataSamples.GetDocumentInstance().OpenResourceAsStream("WordWithAttachments.docx") ); Test(doc, 5); }
public static XWPFDocument WriteOutAndReadBack(XWPFDocument doc) { MemoryStream baos = new MemoryStream(4096); doc.Write(baos); MemoryStream bais = new MemoryStream(baos.ToArray()); return new XWPFDocument(bais); }
public void SetUp() { XWPFDocument doc = new XWPFDocument(); p = doc.CreateParagraph(); this.ctRun = new CT_R(); }
static void Main(string[] args) { if (args.Length != 2) return; string src = args[0]; string target = args[1]; RunMode mode= RunMode.Excel; if (src.Contains(".docx")) mode = RunMode.Word; if (mode == RunMode.Excel) { Stream rfs = File.OpenRead(src); IWorkbook workbook = new XSSFWorkbook(rfs); rfs.Close(); using (FileStream fs = File.Create(target)) { workbook.Write(fs); } } else { Stream rfs = File.OpenRead(src); XWPFDocument workbook = new XWPFDocument(rfs); rfs.Close(); using (FileStream fs = File.Create(target)) { workbook.Write(fs); } } }
static void Main(string[] args) { XWPFDocument doc = new XWPFDocument(); doc.CreateParagraph(); FileStream sw = File.OpenWrite("blank.docx"); doc.Write(sw); sw.Close(); }
/** * If this Hyperlink is an external reference hyperlink, * return the object for it. */ public XWPFHyperlink GetHyperlink(XWPFDocument document) { String id = GetHyperlinkId(); if (id == null) return null; return document.GetHyperlinkByID(id); }
static void Main(string[] args) { XWPFDocument wordDocument = new XWPFDocument(new FileStream("data/Working with Footers.doc", FileMode.Open)); IList<XWPFFooter> footers = wordDocument.FooterList; foreach (XWPFFooter footer in footers) { Console.WriteLine(footer.Text); } }
public void SetUp() { noHeader = XWPFTestDataSamples.OpenSampleDocument("NoHeadFoot.docx"); header = XWPFTestDataSamples.OpenSampleDocument("ThreeColHead.docx"); headerFooter = XWPFTestDataSamples.OpenSampleDocument("SimpleHeadThreeColFoot.docx"); footer = XWPFTestDataSamples.OpenSampleDocument("FancyFoot.docx"); oddEven = XWPFTestDataSamples.OpenSampleDocument("PageSpecificHeadFoot.docx"); diffFirst = XWPFTestDataSamples.OpenSampleDocument("DiffFirstPageHeadFoot.docx"); }
static void Main(string[] args) { XWPFDocument doc = new XWPFDocument(); doc.CreateParagraph(); using (FileStream sw = File.Create("blank.docx")) { doc.Write(sw); } }
public static String Extract(String url, String saveTo = null) { try { WebClient wc = new WebClient(); byte[] data = wc.DownloadData(url); // 如果设置了保存到文件,则写入文件 if (!String.IsNullOrWhiteSpace(saveTo) && data != null && data.Length > 0) { if (!Directory.Exists(saveTo)) { Directory.CreateDirectory(saveTo); } String file = GeneratePath(saveTo, url); try { using (FileStream fs = new FileStream(file, FileMode.CreateNew)) { fs.Write(data, 0, data.Length); } } catch (IOException ioe) { } } using (MemoryStream ms = new MemoryStream(data)) { XWPFDocument doc = new XWPFDocument(ms); StringBuilder wholeDocument = new StringBuilder(); foreach (XWPFParagraph para in doc.Paragraphs) { String text = para.Text; wholeDocument.Append(text); } foreach (XWPFTable table in doc.Tables) { String text = table.Text; if (!String.IsNullOrWhiteSpace(text)) { text = text.Replace("\t", String.Empty); } wholeDocument.Append(text); } return wholeDocument.ToString(); } } catch (Exception e) { return String.Empty; } }
public string Parse() { if (!File.Exists(Context.Path)) throw new FileNotFoundException("File " + Context.Path + " is not found"); bool extractHeader = false; if (Context.Properties.ContainsKey("ExtractHeader")) { extractHeader = Utility.IsTrue(Context.Properties["ExtractHeader"]); } bool extractFooter = false; if (Context.Properties.ContainsKey("ExtractFooter")) { extractFooter = Utility.IsTrue(Context.Properties["ExtractFooter"]); } StringBuilder sb = new StringBuilder(); using (FileStream stream = File.OpenRead(Context.Path)) { XWPFDocument worddoc = new XWPFDocument(stream); if (extractHeader && worddoc.HeaderList!=null) { foreach (var header in worddoc.HeaderList) { sb.Append("[Header] "); sb.AppendLine(header.Text); } } foreach (var elem in worddoc.BodyElements) { if (elem is XWPFParagraph) { XWPFParagraph para = elem as XWPFParagraph; string text = para.ParagraphText; sb.AppendLine(text); } else if (elem is XWPFTable) { XWPFTable table = elem as XWPFTable; string text = table.Text; sb.AppendLine(text); } } if (extractFooter && worddoc.FooterList != null) { foreach (var footer in worddoc.FooterList) { sb.Append("[Footer] "); sb.AppendLine(footer.Text); } } } return sb.ToString(); }
static void Main(string[] args) { string filePath = Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory())) + @"\data\" + "Footers.doc"; // NPOI library doest not have ablitity to read word document. XWPFDocument wordDocument = new XWPFDocument(new FileStream(filePath, FileMode.Open)); IList<XWPFFooter> footers = wordDocument.FooterList; foreach (XWPFFooter footer in footers) { Console.WriteLine(footer.Text); } }
public XWPFHeaderFooter(XWPFDocument doc, CT_HdrFtr hdrFtr) { if (doc == null) { throw new NullReferenceException(); } document = doc; headerFooter = hdrFtr; ReadHdrFtr(); }
public XWPFHeaderFooter(POIXMLDocumentPart parent, PackagePart part, PackageRelationship rel) : base(parent, part, rel) { ; this.document = (XWPFDocument)GetParent(); if (this.document == null) { throw new NullReferenceException(); } }
public void TestTblGrid() { XWPFDocument doc = new XWPFDocument(); CT_Tbl ctTable = new CT_Tbl(); CT_TblGrid cttblgrid = ctTable.AddNewTblGrid(); cttblgrid.AddNewGridCol().w = 123; cttblgrid.AddNewGridCol().w = 321; XWPFTable xtab = new XWPFTable(ctTable, doc); Assert.AreEqual(123, xtab.GetCTTbl().tblGrid.gridCol[0].w); Assert.AreEqual(321, xtab.GetCTTbl().tblGrid.gridCol[1].w); }
public XWPFComment(CT_Comment comment, XWPFDocument document) { text = new StringBuilder(); id = comment.id.ToString(); author = comment.author; foreach(CT_P ctp in comment.GetPList()) { XWPFParagraph p = new XWPFParagraph(ctp, document); text.Append(p.Text); } }
public void TestGetText() { XWPFDocument doc = new XWPFDocument(); CT_Tbl table = new CT_Tbl(); CT_Row row = table.AddNewTr(); CT_Tc cell = row.AddNewTc(); CT_P paragraph = cell.AddNewP(); CT_R run = paragraph.AddNewR(); CT_Text text = run.AddNewT(); text.Value = ("finally I can Write!"); XWPFTable xtab = new XWPFTable(table, doc); Assert.AreEqual("finally I can Write!\n", xtab.Text); }
public void TestAddParagraph() { XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("sample.docx"); Assert.AreEqual(3, doc.Paragraphs.Count); XWPFParagraph p = doc.CreateParagraph(); Assert.AreEqual(p, doc.Paragraphs[(3)]); Assert.AreEqual(4, doc.Paragraphs.Count); Assert.AreEqual(3, doc.GetParagraphPos(3)); Assert.AreEqual(3, doc.GetPosOfParagraph(p)); //CTP ctp = p.CTP; //XWPFParagraph newP = doc.GetParagraph(ctp); //Assert.AreSame(p, newP); //XmlCursor cursor = doc.Document.Body.GetPArray(0).newCursor(); //XWPFParagraph cP = doc.InsertNewParagraph(cursor); //Assert.AreSame(cP, doc.Paragraphs[(0)]); //Assert.AreEqual(5, doc.Paragraphs.Count); }
public void TestGetUsedStyles() { XWPFDocument sampleDoc = XWPFTestDataSamples.OpenSampleDocument("Styles.docx"); List <XWPFStyle> testUsedStyleList = new List <XWPFStyle>(); XWPFStyles styles = sampleDoc.GetStyles(); XWPFStyle style = styles.GetStyle("berschrift1"); testUsedStyleList.Add(style); testUsedStyleList.Add(styles.GetStyle("Standard")); testUsedStyleList.Add(styles.GetStyle("berschrift1Zchn")); testUsedStyleList.Add(styles.GetStyle("Absatz-Standardschriftart")); style.HasSameName(style); List <XWPFStyle> usedStyleList = styles.GetUsedStyleList(style); //Assert.AreEqual(usedStyleList, testUsedStyleList); Assert.AreEqual(usedStyleList.Count, testUsedStyleList.Count); for (int i = 0; i < usedStyleList.Count; i++) { Assert.AreEqual(usedStyleList[i], testUsedStyleList[i]); } }
public void TestSetBorderTop() { //new clean instance of paragraph XWPFDocument doc = new XWPFDocument(); XWPFParagraph p = doc.CreateParagraph(); Assert.AreEqual(ST_Border.none, EnumConverter.ValueOf <ST_Border, Borders>(p.BorderTop)); CT_P ctp = p.GetCTP(); CT_PPr ppr = ctp.pPr == null?ctp.AddNewPPr() : ctp.pPr; //bordi CT_PBdr bdr = ppr.AddNewPBdr(); CT_Border borderTop = bdr.AddNewTop(); borderTop.val = (ST_Border.@double); bdr.top = (borderTop); Assert.AreEqual(Borders.DOUBLE, p.BorderTop); p.BorderTop = (Borders.SINGLE); Assert.AreEqual(ST_Border.single, borderTop.val); }
private void ReadFileText() { var filepath = Request.Params["PlanFilesPath"].Split(',')[0]; var temppath = DownFile(filepath); NPOI.XWPF.UserModel.XWPFDocument doc = null; StringBuilder sbFileText = new StringBuilder(); using (FileStream file = new FileStream(temppath, FileMode.Open, FileAccess.Read)) { doc = new NPOI.XWPF.UserModel.XWPFDocument(file); foreach (NPOI.XWPF.UserModel.XWPFParagraph paragraph in doc.Paragraphs) { sbFileText.AppendLine(paragraph.ParagraphText); } } System.Web.HttpContext.Current.Session["session_filetext"] = sbFileText.ToString(); Response.Clear(); Response.Write(sbFileText.ToString()); Response.ContentType = "text/plain"; Response.End(); }
public void TestSetGetVBorders() { // create a table XWPFDocument doc = new XWPFDocument(); CT_Tbl ctTable = new CT_Tbl(); XWPFTable table = new XWPFTable(ctTable, doc); // Set inside vertical border table.SetInsideVBorder(NPOI.XWPF.UserModel.XWPFTable.XWPFBorderType.DOUBLE, 4, 0, "00FF00"); // Get inside vertical border components NPOI.XWPF.UserModel.XWPFTable.XWPFBorderType bt = table.InsideVBorderType; Assert.AreEqual(NPOI.XWPF.UserModel.XWPFTable.XWPFBorderType.DOUBLE, bt); int sz = table.InsideVBorderSize; Assert.AreEqual(4, sz); int sp = table.InsideVBorderSpace; Assert.AreEqual(0, sp); String clr = table.InsideVBorderColor; Assert.AreEqual("00FF00", clr); }
public void TestBug58922() { XWPFDocument document = new XWPFDocument(); XWPFRun run = document.CreateParagraph().CreateRun(); Assert.AreEqual(-1, run.FontSize); run.FontSize = 10; Assert.AreEqual(10, run.FontSize); run.FontSize = short.MaxValue - 1; Assert.AreEqual(short.MaxValue - 1, run.FontSize); run.FontSize = short.MaxValue; Assert.AreEqual(short.MaxValue, run.FontSize); run.FontSize = short.MaxValue + 1; Assert.AreEqual(short.MaxValue + 1, run.FontSize); run.FontSize = int.MaxValue - 1; Assert.AreEqual(int.MaxValue - 1, run.FontSize); run.FontSize = int.MaxValue; Assert.AreEqual(int.MaxValue, run.FontSize); run.FontSize = -1; Assert.AreEqual(-1, run.FontSize); Assert.AreEqual(-1, run.TextPosition); run.TextPosition = 10; Assert.AreEqual(10, run.TextPosition); run.TextPosition = short.MaxValue - 1; Assert.AreEqual(short.MaxValue - 1, run.TextPosition); run.TextPosition = short.MaxValue; Assert.AreEqual(short.MaxValue, run.TextPosition); run.TextPosition = short.MaxValue + 1; Assert.AreEqual(short.MaxValue + 1, run.TextPosition); run.TextPosition = short.MaxValue + 1; Assert.AreEqual(short.MaxValue + 1, run.TextPosition); run.TextPosition = int.MaxValue - 1; Assert.AreEqual(int.MaxValue - 1, run.TextPosition); run.TextPosition = int.MaxValue; Assert.AreEqual(int.MaxValue, run.TextPosition); run.TextPosition = -1; Assert.AreEqual(-1, run.TextPosition); }
public void TestSDTAsCell() { //Bug54771a.docx and Bug54771b.docx test slightly //different recursion patterns. Keep both! XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("Bug54771a.docx"); List <AbstractXWPFSDT> sdts = ExtractAllSDTs(doc); String text = sdts[(0)].Content.Text; Assert.AreEqual(2, sdts.Count); Assert.IsTrue(text.IndexOf("Test") > -1); text = sdts[(1)].Content.Text; Assert.IsTrue(text.IndexOf("Test Subtitle") > -1); Assert.IsTrue(text.IndexOf("Test User") > -1); Assert.IsTrue(text.IndexOf("Test") < text.IndexOf("Test Subtitle")); doc = XWPFTestDataSamples.OpenSampleDocument("Bug54771b.docx"); sdts = ExtractAllSDTs(doc); Assert.AreEqual(3, sdts.Count); Assert.IsTrue(sdts[0].Content.Text.IndexOf("Test") > -1); Assert.IsTrue(sdts[(1)].Content.Text.IndexOf("Test Subtitle") > -1); Assert.IsTrue(sdts[(2)].Content.Text.IndexOf("Test User") > -1); }
public void TestNewLinesBetweenRuns() { XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("Bug55142.docx"); List <AbstractXWPFSDT> sdts = ExtractAllSDTs(doc); List <String> targs = new List <String>(); //these test newlines and tabs in paragraphs/body elements targs.Add("Rich-text1 abcdefghi"); targs.Add("Rich-text2 abcd\t\tefgh"); targs.Add("Rich-text3 abcd\nefg"); targs.Add("Rich-text4 abcdefg"); targs.Add("Rich-text5 abcdefg\nhijk"); targs.Add("Plain-text1 abcdefg"); targs.Add("Plain-text2 abcdefg\nhijk\nlmnop"); //this tests consecutive runs within a cell (not a paragraph) //this test case was triggered by Tika-1130 targs.Add("sdt_incell2 abcdefg"); for (int i = 0; i < sdts.Count; i++) { AbstractXWPFSDT sdt = sdts[i]; Assert.AreEqual(targs[i], sdt.Content.Text, targs[i]); } }
public void TestDocumentParagraph() { XWPFDocument xml = XWPFTestDataSamples.OpenSampleDocument("ThreeColHead.docx"); IList <XWPFParagraph> ps = xml.Paragraphs; Assert.AreEqual(10, ps.Count); Assert.IsFalse(ps[(0)].IsEmpty); Assert.AreEqual( "This is a sample word document. It has two pages. It has a three column heading, but no footer.", ps[(0)].Text); Assert.IsTrue(ps[1].IsEmpty); Assert.AreEqual("", ps[1].Text); Assert.IsFalse(ps[2].IsEmpty); Assert.AreEqual("HEADING TEXT", ps[2].Text); Assert.IsTrue(ps[3].IsEmpty); Assert.AreEqual("", ps[3].Text); Assert.IsFalse(ps[4].IsEmpty); Assert.AreEqual("More on page one", ps[4].Text); }
public XWPFParagraph(CT_P prgrph, IBody part) { this.paragraph = prgrph; this.part = part; this.document = part.GetXWPFDocument(); if (document == null) { throw new NullReferenceException(); } // Build up the character runs runs = new List <XWPFRun>(); BuildRunsInOrderFromXml(paragraph.Items); // Look for bits associated with the runs foreach (XWPFRun run in runs) { CT_R r = run.GetCTR(); if (document != null) { for (int i = 0; i < r.Items.Count; i++) { object o = r.Items[i]; if (o is CT_FtnEdnRef) { CT_FtnEdnRef ftn = (CT_FtnEdnRef)o; footnoteText.Append("[").Append(ftn.id).Append(": "); XWPFFootnote footnote = null; if (r.ItemsElementName.Count > i && r.ItemsElementName[i] == RunItemsChoiceType.endnoteReference) { footnote = document.GetEndnoteByID(int.Parse(ftn.id)); if (footnote == null) { footnote = document.GetFootnoteByID(int.Parse(ftn.id)); } } else { footnote = document.GetFootnoteByID(int.Parse(ftn.id)); if (footnote == null) { footnote = document.GetEndnoteByID(int.Parse(ftn.id)); } } if (footnote != null) { bool first = true; foreach (XWPFParagraph p in footnote.Paragraphs) { if (!first) { footnoteText.Append("\n"); first = false; } footnoteText.Append(p.Text); } } footnoteText.Append("]"); } } } } // Get all our child nodes in order, and process them // into XWPFRuns where we can /*XmlCursor c = paragraph.NewCursor(); * c.SelectPath("child::*"); * while (c.ToNextSelection()) { * XmlObject o = c.Object; * if(o is CT_R) { * Runs.Add(new XWPFRun((CT_R)o, this)); * } * if(o is CT_Hyperlink) { * CT_Hyperlink link = (CT_Hyperlink)o; * foreach(CTR r in link.RList) { * Runs.Add(new XWPFHyperlinkRun(link, r, this)); * } * } * if(o is CT_SdtRun) { * CT_SdtContentRun run = ((CT_SdtRun)o).SdtContent; * foreach(CTR r in Run.RList) { * Runs.Add(new XWPFRun(r, this)); * } * } * if(o is CT_RunTrackChange) { * foreach(CTR r in ((CT_RunTrackChange)o).RList) { * Runs.Add(new XWPFRun(r, this)); * } * } * if(o is CT_SimpleField) { * foreach(CTR r in ((CT_SimpleField)o).RList) { * Runs.Add(new XWPFRun(r, this)); * } * } * }*/ }
public void SetXWPFDocument(XWPFDocument doc) { this.document = doc; }
public void TestNew() { XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("EmptyDocumentWithHeaderFooter.docx"); byte[] jpegData = XWPFTestDataSamples.GetImage("nature1.jpg"); Assert.IsNotNull(jpegData); byte[] gifData = XWPFTestDataSamples.GetImage("nature1.gif"); Assert.IsNotNull(gifData); byte[] pngData = XWPFTestDataSamples.GetImage("nature1.png"); Assert.IsNotNull(pngData); IList <XWPFPictureData> pictures = doc.AllPictures; Assert.AreEqual(0, pictures.Count); // Document shouldn't have any image relationships Assert.AreEqual(13, doc.GetPackagePart().Relationships.Size); foreach (PackageRelationship rel in doc.GetPackagePart().Relationships) { if (rel.RelationshipType.Equals(XSSFRelation.IMAGE_JPEG.Relation)) { Assert.Fail("Shouldn't have JPEG yet"); } } // Add the image String relationId = doc.AddPictureData(jpegData, (int)PictureType.JPEG); Assert.AreEqual(1, pictures.Count); XWPFPictureData jpgPicData = (XWPFPictureData)doc.GetRelationById(relationId); Assert.AreEqual("jpeg", jpgPicData.SuggestFileExtension()); Assert.IsTrue(Arrays.Equals(jpegData, jpgPicData.Data)); // Ensure it now has one Assert.AreEqual(14, doc.GetPackagePart().Relationships.Size); PackageRelationship jpegRel = null; foreach (PackageRelationship rel in doc.GetPackagePart().Relationships) { if (rel.RelationshipType.Equals(XWPFRelation.IMAGE_JPEG.Relation)) { if (jpegRel != null) { Assert.Fail("Found 2 jpegs!"); } jpegRel = rel; } } Assert.IsNotNull(jpegRel, "JPEG Relationship not found"); // Check the details Assert.AreEqual(XWPFRelation.IMAGE_JPEG.Relation, jpegRel.RelationshipType); Assert.AreEqual("/word/document.xml", jpegRel.Source.PartName.ToString()); Assert.AreEqual("/word/media/image1.jpeg", jpegRel.TargetUri.OriginalString); XWPFPictureData pictureDataByID = doc.GetPictureDataByID(jpegRel.Id); Assert.IsTrue(Arrays.Equals(jpegData, pictureDataByID.Data)); // Save an re-load, check it appears doc = XWPFTestDataSamples.WriteOutAndReadBack(doc); Assert.AreEqual(1, doc.AllPictures.Count); Assert.AreEqual(1, doc.AllPackagePictures.Count); // verify the picture that we read back in pictureDataByID = doc.GetPictureDataByID(jpegRel.Id); Assert.IsTrue(Arrays.Equals(jpegData, pictureDataByID.Data)); }
/** * Adds a picture to the run. This method handles * attaching the picture data to the overall file. * * @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_EMF * @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_WMF * @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_PICT * @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_JPEG * @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_PNG * @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_DIB * * @param pictureData The raw picture data * @param pictureType The type of the picture, eg {@link Document#PICTURE_TYPE_JPEG} * @param width width in EMUs. To convert to / from points use {@link org.apache.poi.util.Units} * @param height height in EMUs. To convert to / from points use {@link org.apache.poi.util.Units} * @throws NPOI.Openxml4j.exceptions.InvalidFormatException * @throws IOException */ public XWPFPicture AddPicture(Stream pictureData, int pictureType, String filename, int width, int height) { XWPFDocument doc = parent.Document; // Add the picture + relationship String relationId = doc.AddPictureData(pictureData, pictureType); XWPFPictureData picData = (XWPFPictureData)doc.GetRelationById(relationId); // Create the Drawing entry for it CT_Drawing Drawing = run.AddNewDrawing(); CT_Inline inline = Drawing.AddNewInline(); // Do the fiddly namespace bits on the inline // (We need full control of what goes where and as what) //CT_GraphicalObject tmp = new CT_GraphicalObject(); //String xml = // "<a:graphic xmlns:a=\"" + "http://schemas.openxmlformats.org/drawingml/2006/main" + "\">" + // "<a:graphicData uri=\"" + "http://schemas.openxmlformats.org/drawingml/2006/picture" + "\">" + // "<pic:pic xmlns:pic=\"" + "http://schemas.openxmlformats.org/drawingml/2006/picture" + "\" />" + // "</a:graphicData>" + // "</a:graphic>"; //inline.Set((xml)); XmlDocument xmlDoc = new XmlDocument(); //XmlElement el = xmlDoc.CreateElement("pic", "pic", "http://schemas.openxmlformats.org/drawingml/2006/picture"); inline.graphic = new CT_GraphicalObject(); inline.graphic.graphicData = new CT_GraphicalObjectData(); inline.graphic.graphicData.uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"; // Setup the inline inline.distT = (0); inline.distR = (0); inline.distB = (0); inline.distL = (0); NPOI.OpenXmlFormats.Dml.WordProcessing.CT_NonVisualDrawingProps docPr = inline.AddNewDocPr(); long id = parent.Document.DrawingIdManager.ReserveNew(); docPr.id = (uint)(id); /* This name is not visible in Word 2010 anywhere. */ docPr.name = ("Drawing " + id); docPr.descr = (filename); NPOI.OpenXmlFormats.Dml.WordProcessing.CT_PositiveSize2D extent = inline.AddNewExtent(); extent.cx = (width); extent.cy = (height); // Grab the picture object NPOI.OpenXmlFormats.Dml.Picture.CT_Picture pic = new OpenXmlFormats.Dml.Picture.CT_Picture(); // Set it up NPOI.OpenXmlFormats.Dml.Picture.CT_PictureNonVisual nvPicPr = pic.AddNewNvPicPr(); NPOI.OpenXmlFormats.Dml.CT_NonVisualDrawingProps cNvPr = nvPicPr.AddNewCNvPr(); /* use "0" for the id. See ECM-576, 20.2.2.3 */ cNvPr.id = (0); /* This name is not visible in Word 2010 anywhere */ cNvPr.name = ("Picture " + id); cNvPr.descr = (filename); CT_NonVisualPictureProperties cNvPicPr = nvPicPr.AddNewCNvPicPr(); cNvPicPr.AddNewPicLocks().noChangeAspect = true; CT_BlipFillProperties blipFill = pic.AddNewBlipFill(); CT_Blip blip = blipFill.AddNewBlip(); blip.embed = (picData.GetPackageRelationship().Id); blipFill.AddNewStretch().AddNewFillRect(); CT_ShapeProperties spPr = pic.AddNewSpPr(); CT_Transform2D xfrm = spPr.AddNewXfrm(); CT_Point2D off = xfrm.AddNewOff(); off.x = (0); off.y = (0); NPOI.OpenXmlFormats.Dml.CT_PositiveSize2D ext = xfrm.AddNewExt(); ext.cx = (width); ext.cy = (height); CT_PresetGeometry2D prstGeom = spPr.AddNewPrstGeom(); prstGeom.prst = (ST_ShapeType.rect); prstGeom.AddNewAvLst(); using (var ms = new MemoryStream()) { StreamWriter sw = new StreamWriter(ms); pic.Write(sw, "pic:pic"); sw.Flush(); ms.Position = 0; var sr = new StreamReader(ms); var picXml = sr.ReadToEnd(); inline.graphic.graphicData.AddPicElement(picXml); } // Finish up XWPFPicture xwpfPicture = new XWPFPicture(pic, this); pictures.Add(xwpfPicture); return(xwpfPicture); }
XWPFPicture AddPicture(Stream pictureData, int pictureType, String filename, int width, int height, Action <XWPFDocument, CT_Blip> extAct) { // Add the picture + relationship String relationId; XWPFPictureData picData; XWPFDocument doc = null; // Work out what to add the picture to, then add both the // picture and the relationship for it // TODO Should we have an interface for this sort of thing? if (parent.Part is XWPFHeaderFooter) { XWPFHeaderFooter headerFooter = (XWPFHeaderFooter)parent.Part; relationId = headerFooter.AddPictureData(pictureData, pictureType); picData = (XWPFPictureData)headerFooter.GetRelationById(relationId); } else { doc = parent.Document; relationId = doc.AddPictureData(pictureData, pictureType); picData = (XWPFPictureData)doc.GetRelationById(relationId); } try { // Create the Drawing entry for it CT_Drawing Drawing = run.AddNewDrawing(); CT_Inline inline = Drawing.AddNewInline(); // Do the fiddly namespace bits on the inline // (We need full control of what goes where and as what) //CT_GraphicalObject tmp = new CT_GraphicalObject(); //String xml = // "<a:graphic xmlns:a=\"" + "http://schemas.openxmlformats.org/drawingml/2006/main" + "\">" + // "<a:graphicData uri=\"" + "http://schemas.openxmlformats.org/drawingml/2006/picture" + "\">" + // "<pic:pic xmlns:pic=\"" + "http://schemas.openxmlformats.org/drawingml/2006/picture" + "\" />" + // "</a:graphicData>" + // "</a:graphic>"; //InputSource is = new InputSource(new StringReader(xml)); //org.w3c.dom.Document doc = DocumentHelper.readDocument(is); //inline.set(XmlToken.Factory.parse(doc.getDocumentElement(), DEFAULT_XML_OPTIONS)); inline.graphic = new CT_GraphicalObject(); inline.graphic.graphicData = new CT_GraphicalObjectData(); inline.graphic.graphicData.uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"; // Setup the inline inline.distT = (0); inline.distR = (0); inline.distB = (0); inline.distL = (0); NPOI.OpenXmlFormats.Dml.WordProcessing.CT_NonVisualDrawingProps docPr = inline.AddNewDocPr(); long id = parent.Document.DrawingIdManager.ReserveNew(); docPr.id = (uint)(id); /* This name is not visible in Word 2010 anywhere. */ docPr.name = ("Drawing " + id); docPr.descr = (filename); NPOI.OpenXmlFormats.Dml.WordProcessing.CT_PositiveSize2D extent = inline.AddNewExtent(); extent.cx = (width); extent.cy = (height); // Grab the picture object NPOI.OpenXmlFormats.Dml.Picture.CT_Picture pic = new OpenXmlFormats.Dml.Picture.CT_Picture(); // Set it up NPOI.OpenXmlFormats.Dml.Picture.CT_PictureNonVisual nvPicPr = pic.AddNewNvPicPr(); NPOI.OpenXmlFormats.Dml.CT_NonVisualDrawingProps cNvPr = nvPicPr.AddNewCNvPr(); /* use "0" for the id. See ECM-576, 20.2.2.3 */ cNvPr.id = (0); /* This name is not visible in Word 2010 anywhere */ cNvPr.name = ("Picture " + id); cNvPr.descr = (filename); CT_NonVisualPictureProperties cNvPicPr = nvPicPr.AddNewCNvPicPr(); cNvPicPr.AddNewPicLocks().noChangeAspect = true; CT_BlipFillProperties blipFill = pic.AddNewBlipFill(); CT_Blip blip = blipFill.AddNewBlip(); blip.embed = (picData.GetPackageRelationship().Id); if (doc != null) { extAct(doc, blip); } blipFill.AddNewStretch().AddNewFillRect(); CT_ShapeProperties spPr = pic.AddNewSpPr(); CT_Transform2D xfrm = spPr.AddNewXfrm(); CT_Point2D off = xfrm.AddNewOff(); off.x = (0); off.y = (0); NPOI.OpenXmlFormats.Dml.CT_PositiveSize2D ext = xfrm.AddNewExt(); ext.cx = (width); ext.cy = (height); CT_PresetGeometry2D prstGeom = spPr.AddNewPrstGeom(); prstGeom.prst = (ST_ShapeType.rect); prstGeom.AddNewAvLst(); using (var ms = new MemoryStream()) { StreamWriter sw = new StreamWriter(ms); pic.Write(sw, "pic:pic"); sw.Flush(); ms.Position = 0; var sr = new StreamReader(ms); var picXml = sr.ReadToEnd(); inline.graphic.graphicData.AddPicElement(picXml); } // Finish up XWPFPicture xwpfPicture = new XWPFPicture(pic, this); pictures.Add(xwpfPicture); return(xwpfPicture); } catch (XmlException e) { throw new InvalidOperationException("XWPFRun.Addpicture error", e); } }
public void TestExisting() { XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("TestDocument.docx"); XWPFParagraph p; XWPFRun run; // First paragraph is simple p = doc.GetParagraphArray(0); Assert.AreEqual("This is a test document.", p.GetText()); Assert.AreEqual(2, p.GetRuns().Count); run = p.GetRuns()[0]; Assert.AreEqual("This is a test document", run.ToString()); Assert.AreEqual(false, run.IsBold()); Assert.AreEqual(false, run.IsItalic()); Assert.AreEqual(false, run.IsStrike()); Assert.AreEqual(null, run.GetCTR().rPr); run = p.GetRuns()[1]; Assert.AreEqual(".", run.ToString()); Assert.AreEqual(false, run.IsBold()); Assert.AreEqual(false, run.IsItalic()); Assert.AreEqual(false, run.IsStrike()); Assert.AreEqual(null, run.GetCTR().rPr); // Next paragraph is all in one style, but a different one p = doc.GetParagraphArray(1); Assert.AreEqual("This bit is in bold and italic", p.GetText()); Assert.AreEqual(1, p.GetRuns().Count); run = p.GetRuns()[0]; Assert.AreEqual("This bit is in bold and italic", run.ToString()); Assert.AreEqual(true, run.IsBold()); Assert.AreEqual(true, run.IsItalic()); Assert.AreEqual(false, run.IsStrike()); Assert.AreEqual(true, run.GetCTR().rPr.IsSetB()); Assert.AreEqual(false, run.GetCTR().rPr.b.IsSetVal()); // Back to normal p = doc.GetParagraphArray(2); Assert.AreEqual("Back to normal", p.GetText()); Assert.AreEqual(1, p.GetRuns().Count); run = p.GetRuns()[(0)]; Assert.AreEqual("Back to normal", run.ToString()); Assert.AreEqual(false, run.IsBold()); Assert.AreEqual(false, run.IsItalic()); Assert.AreEqual(false, run.IsStrike()); Assert.AreEqual(null, run.GetCTR().rPr); // Different styles in one paragraph p = doc.GetParagraphArray(3); Assert.AreEqual("This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.", p.GetText()); Assert.AreEqual(11, p.GetRuns().Count); run = p.GetRuns()[(0)]; Assert.AreEqual("This contains ", run.ToString()); Assert.AreEqual(false, run.IsBold()); Assert.AreEqual(false, run.IsItalic()); Assert.AreEqual(false, run.IsStrike()); Assert.AreEqual(null, run.GetCTR().rPr); run = p.GetRuns()[(1)]; Assert.AreEqual("BOLD", run.ToString()); Assert.AreEqual(true, run.IsBold()); Assert.AreEqual(false, run.IsItalic()); Assert.AreEqual(false, run.IsStrike()); run = p.GetRuns()[2]; Assert.AreEqual(", ", run.ToString()); Assert.AreEqual(false, run.IsBold()); Assert.AreEqual(false, run.IsItalic()); Assert.AreEqual(false, run.IsStrike()); Assert.AreEqual(null, run.GetCTR().rPr); run = p.GetRuns()[(3)]; Assert.AreEqual("ITALIC", run.ToString()); Assert.AreEqual(false, run.IsBold()); Assert.AreEqual(true, run.IsItalic()); Assert.AreEqual(false, run.IsStrike()); run = p.GetRuns()[(4)]; Assert.AreEqual(" and ", run.ToString()); Assert.AreEqual(false, run.IsBold()); Assert.AreEqual(false, run.IsItalic()); Assert.AreEqual(false, run.IsStrike()); Assert.AreEqual(null, run.GetCTR().rPr); run = p.GetRuns()[(5)]; Assert.AreEqual("BOTH", run.ToString()); Assert.AreEqual(true, run.IsBold()); Assert.AreEqual(true, run.IsItalic()); Assert.AreEqual(false, run.IsStrike()); run = p.GetRuns()[(6)]; Assert.AreEqual(", as well as ", run.ToString()); Assert.AreEqual(false, run.IsBold()); Assert.AreEqual(false, run.IsItalic()); Assert.AreEqual(false, run.IsStrike()); Assert.AreEqual(null, run.GetCTR().rPr); run = p.GetRuns()[(7)]; Assert.AreEqual("RED", run.ToString()); Assert.AreEqual(false, run.IsBold()); Assert.AreEqual(false, run.IsItalic()); Assert.AreEqual(false, run.IsStrike()); run = p.GetRuns()[(8)]; Assert.AreEqual(" and ", run.ToString()); Assert.AreEqual(false, run.IsBold()); Assert.AreEqual(false, run.IsItalic()); Assert.AreEqual(false, run.IsStrike()); Assert.AreEqual(null, run.GetCTR().rPr); run = p.GetRuns()[(9)]; Assert.AreEqual("YELLOW", run.ToString()); Assert.AreEqual(false, run.IsBold()); Assert.AreEqual(false, run.IsItalic()); Assert.AreEqual(false, run.IsStrike()); run = p.GetRuns()[(10)]; Assert.AreEqual(" text.", run.ToString()); Assert.AreEqual(false, run.IsBold()); Assert.AreEqual(false, run.IsItalic()); Assert.AreEqual(false, run.IsStrike()); Assert.AreEqual(null, run.GetCTR().rPr); }
public XWPFFootnote(XWPFDocument document, CT_FtnEdn body) { ctFtnEdn = body; this.document = document; Init(); }
public XWPFParagraph(CT_P prgrph, IBody part) { this.paragraph = prgrph; this.part = part; this.document = part.GetXWPFDocument(); if (document == null) { throw new NullReferenceException(); } // Build up the character runs runs = new List <XWPFRun>(); iRuns = new List <IRunElement>(); BuildRunsInOrderFromXml(paragraph.Items); // Look for bits associated with the runs foreach (XWPFRun run in runs) { CT_R r = run.GetCTR(); if (document != null) { for (int i = 0; i < r.Items.Count; i++) { object o = r.Items[i]; if (o is CT_FtnEdnRef) { CT_FtnEdnRef ftn = (CT_FtnEdnRef)o; footnoteText.Append("[").Append(ftn.id).Append(": "); XWPFFootnote footnote = null; if (r.ItemsElementName.Count > i && r.ItemsElementName[i] == RunItemsChoiceType.endnoteReference) { footnote = document.GetEndnoteByID(int.Parse(ftn.id)); if (footnote == null) { footnote = document.GetFootnoteByID(int.Parse(ftn.id)); } } else { footnote = document.GetFootnoteByID(int.Parse(ftn.id)); if (footnote == null) { footnote = document.GetEndnoteByID(int.Parse(ftn.id)); } } if (footnote != null) { bool first = true; foreach (XWPFParagraph p in footnote.Paragraphs) { if (!first) { footnoteText.Append("\n"); first = false; } footnoteText.Append(p.Text); } } footnoteText.Append("]"); } } } } }
public void TestRemoveBodyElement() { XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("sample.docx"); Assert.AreEqual(3, doc.Paragraphs.Count); Assert.AreEqual(3, doc.BodyElements.Count); XWPFParagraph p1 = doc.Paragraphs[(0)]; XWPFParagraph p2 = doc.Paragraphs[(1)]; XWPFParagraph p3 = doc.Paragraphs[(2)]; Assert.AreEqual(p1, doc.BodyElements[(0)]); Assert.AreEqual(p1, doc.Paragraphs[(0)]); Assert.AreEqual(p2, doc.BodyElements[(1)]); Assert.AreEqual(p2, doc.Paragraphs[(1)]); Assert.AreEqual(p3, doc.BodyElements[(2)]); Assert.AreEqual(p3, doc.Paragraphs[(2)]); // Add another XWPFParagraph p4 = doc.CreateParagraph(); Assert.AreEqual(4, doc.Paragraphs.Count); Assert.AreEqual(4, doc.BodyElements.Count); Assert.AreEqual(p1, doc.BodyElements[(0)]); Assert.AreEqual(p1, doc.Paragraphs[(0)]); Assert.AreEqual(p2, doc.BodyElements[(1)]); Assert.AreEqual(p2, doc.Paragraphs[(1)]); Assert.AreEqual(p3, doc.BodyElements[(2)]); Assert.AreEqual(p3, doc.Paragraphs[(2)]); Assert.AreEqual(p4, doc.BodyElements[(3)]); Assert.AreEqual(p4, doc.Paragraphs[(3)]); // Remove the 2nd Assert.AreEqual(true, doc.RemoveBodyElement(1)); Assert.AreEqual(3, doc.Paragraphs.Count); Assert.AreEqual(3, doc.BodyElements.Count); Assert.AreEqual(p1, doc.BodyElements[(0)]); Assert.AreEqual(p1, doc.Paragraphs[(0)]); Assert.AreEqual(p3, doc.BodyElements[(1)]); Assert.AreEqual(p3, doc.Paragraphs[(1)]); Assert.AreEqual(p4, doc.BodyElements[(2)]); Assert.AreEqual(p4, doc.Paragraphs[(2)]); // Remove the 1st Assert.AreEqual(true, doc.RemoveBodyElement(0)); Assert.AreEqual(2, doc.Paragraphs.Count); Assert.AreEqual(2, doc.BodyElements.Count); Assert.AreEqual(p3, doc.BodyElements[(0)]); Assert.AreEqual(p3, doc.Paragraphs[(0)]); Assert.AreEqual(p4, doc.BodyElements[(1)]); Assert.AreEqual(p4, doc.Paragraphs[(1)]); // Remove the last Assert.AreEqual(true, doc.RemoveBodyElement(1)); Assert.AreEqual(1, doc.Paragraphs.Count); Assert.AreEqual(1, doc.BodyElements.Count); Assert.AreEqual(p3, doc.BodyElements[(0)]); Assert.AreEqual(p3, doc.Paragraphs[(0)]); }
public void TestSetHeader() { XWPFDocument sampleDoc = XWPFTestDataSamples.OpenSampleDocument("SampleDoc.docx"); // no header is Set (yet) XWPFHeaderFooterPolicy policy = sampleDoc.GetHeaderFooterPolicy(); Assert.IsNull(policy.GetDefaultHeader()); Assert.IsNull(policy.GetFirstPageHeader()); Assert.IsNull(policy.GetDefaultFooter()); CT_P ctP1 = new CT_P(); CT_R ctR1 = ctP1.AddNewR(); CT_Text t = ctR1.AddNewT(); t.Value = ("Paragraph in header"); // Commented MB 23 May 2010 //CTP ctP2 = CTP.Factory.NewInstance(); //CTR ctR2 = ctP2.AddNewR(); //CTText t2 = ctR2.AddNewT(); //t2.StringValue=("Second paragraph.. for footer"); // Create two paragraphs for insertion into the footer. // Previously only one was inserted MB 23 May 2010 CT_P ctP2 = new CT_P(); CT_R ctR2 = ctP2.AddNewR(); CT_Text t2 = ctR2.AddNewT(); t2.Value = ("First paragraph for the footer"); CT_P ctP3 = new CT_P(); CT_R ctR3 = ctP3.AddNewR(); CT_Text t3 = ctR3.AddNewT(); t3.Value = ("Second paragraph for the footer"); XWPFParagraph p1 = new XWPFParagraph(ctP1, sampleDoc); XWPFParagraph[] pars = new XWPFParagraph[1]; pars[0] = p1; XWPFParagraph p2 = new XWPFParagraph(ctP2, sampleDoc); XWPFParagraph p3 = new XWPFParagraph(ctP3, sampleDoc); XWPFParagraph[] pars2 = new XWPFParagraph[2]; pars2[0] = p2; pars2[1] = p3; // Set headers policy.CreateHeader(XWPFHeaderFooterPolicy.DEFAULT, pars); policy.CreateHeader(XWPFHeaderFooterPolicy.FIRST); // Set a default footer and capture the returned XWPFFooter object. XWPFFooter footer = policy.CreateFooter(XWPFHeaderFooterPolicy.DEFAULT, pars2); // Ensure the headers and footer were Set correctly.... Assert.IsNotNull(policy.GetDefaultHeader()); Assert.IsNotNull(policy.GetFirstPageHeader()); Assert.IsNotNull(policy.GetDefaultFooter()); // ....and that the footer object captured above Contains two // paragraphs of text. Assert.AreEqual(2, footer.Paragraphs.Count); // As an Additional Check, recover the defauls footer and // make sure that it Contains two paragraphs of text and that // both do hold what is expected. footer = policy.GetDefaultFooter(); XWPFParagraph[] paras = new XWPFParagraph[footer.Paragraphs.Count]; int i = 0; foreach (XWPFParagraph p in footer.Paragraphs) { paras[i++] = p; } Assert.AreEqual(2, paras.Length); Assert.AreEqual("First paragraph for the footer", paras[0].Text); Assert.AreEqual("Second paragraph for the footer", paras[1].Text); }
public XWPFDocument() : base(XWPFDocument.newPackage()) { this.OnDocumentCreate(); }
public void Test56392() { XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("56392.docx"); Assert.IsNotNull(doc); }
public void TestSetHeader() { XWPFDocument sampleDoc = XWPFTestDataSamples.OpenSampleDocument("SampleDoc.docx"); // no header is Set (yet) XWPFHeaderFooterPolicy policy = sampleDoc.GetHeaderFooterPolicy(); Assert.IsNull(policy.GetDefaultHeader()); Assert.IsNull(policy.GetFirstPageHeader()); Assert.IsNull(policy.GetDefaultFooter()); CT_P ctP1 = new CT_P(); CT_R ctR1 = ctP1.AddNewR(); CT_Text t = ctR1.AddNewT(); String tText = "Paragraph in header"; t.Value = tText; // Commented MB 23 May 2010 //CTP ctP2 = CTP.Factory.NewInstance(); //CTR ctR2 = ctP2.AddNewR(); //CTText t2 = ctR2.AddNewT(); //t2.StringValue=("Second paragraph.. for footer"); // Create two paragraphs for insertion into the footer. // Previously only one was inserted MB 23 May 2010 CT_P ctP2 = new CT_P(); CT_R ctR2 = ctP2.AddNewR(); CT_Text t2 = ctR2.AddNewT(); t2.Value = ("First paragraph for the footer"); CT_P ctP3 = new CT_P(); CT_R ctR3 = ctP3.AddNewR(); CT_Text t3 = ctR3.AddNewT(); t3.Value = ("Second paragraph for the footer"); XWPFParagraph p1 = new XWPFParagraph(ctP1, sampleDoc); XWPFParagraph[] pars = new XWPFParagraph[1]; pars[0] = p1; XWPFParagraph p2 = new XWPFParagraph(ctP2, sampleDoc); XWPFParagraph p3 = new XWPFParagraph(ctP3, sampleDoc); XWPFParagraph[] pars2 = new XWPFParagraph[2]; pars2[0] = p2; pars2[1] = p3; // Set headers XWPFHeader headerD = policy.CreateHeader(XWPFHeaderFooterPolicy.DEFAULT, pars); XWPFHeader headerF = policy.CreateHeader(XWPFHeaderFooterPolicy.FIRST); // Set a default footer and capture the returned XWPFFooter object. XWPFFooter footer = policy.CreateFooter(XWPFHeaderFooterPolicy.DEFAULT, pars2); // Ensure the headers and footer were Set correctly.... Assert.IsNotNull(policy.GetDefaultHeader()); Assert.IsNotNull(policy.GetFirstPageHeader()); Assert.IsNotNull(policy.GetDefaultFooter()); // ....and that the footer object captured above Contains two // paragraphs of text. Assert.AreEqual(2, footer.Paragraphs.Count); // Check the header created with the paragraph got them, and the one // created without got an empty one Assert.AreEqual(1, headerD.Paragraphs.Count); Assert.AreEqual(1, headerF.Paragraphs.Count); Assert.AreEqual(tText, headerD.Paragraphs[0].Text); Assert.AreEqual("", headerF.Paragraphs[0].Text); // As an Additional Check, recover the defauls footer and // make sure that it Contains two paragraphs of text and that // both do hold what is expected. footer = policy.GetDefaultFooter(); XWPFParagraph[] paras = new List <XWPFParagraph>(footer.Paragraphs).ToArray(); Assert.AreEqual(2, paras.Length); Assert.AreEqual("First paragraph for the footer", paras[0].Text); Assert.AreEqual("Second paragraph for the footer", paras[1].Text); // Add some text to the empty header String fText1 = "New Text!"; headerF.Paragraphs[0].InsertNewRun(0).SetText(fText1); // TODO Add another paragraph and check // Check it Assert.AreEqual(tText, headerD.Paragraphs[0].Text); Assert.AreEqual(fText1, headerF.Paragraphs[0].Text); // Save, re-open, ensure it's all still there XWPFDocument reopened = XWPFTestDataSamples.WriteOutAndReadBack(sampleDoc); policy = reopened.GetHeaderFooterPolicy(); Assert.IsNotNull(policy.GetDefaultHeader()); Assert.IsNotNull(policy.GetFirstPageHeader()); Assert.IsNull(policy.GetEvenPageHeader()); Assert.IsNotNull(policy.GetDefaultFooter()); Assert.IsNull(policy.GetFirstPageFooter()); Assert.IsNull(policy.GetEvenPageFooter()); // Check the new headers still have their text headerD = policy.GetDefaultHeader(); headerF = policy.GetFirstPageHeader(); Assert.AreEqual(tText, headerD.Paragraphs[0].Text); Assert.AreEqual(fText1, headerF.Paragraphs[0].Text); // Check the new footers have their new text too footer = policy.GetDefaultFooter(); paras = new List <XWPFParagraph>(footer.Paragraphs).ToArray(); Assert.AreEqual(2, paras.Length); Assert.AreEqual("First paragraph for the footer", paras[0].Text); Assert.AreEqual("Second paragraph for the footer", paras[1].Text); }
public void TestPictures() { XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("VariousPictures.docx"); Assert.AreEqual(7, doc.Paragraphs.Count); XWPFParagraph p; XWPFRun r; // Text paragraphs Assert.AreEqual("Sheet with various pictures", doc.Paragraphs[0].Text); Assert.AreEqual("(jpeg, png, wmf, emf and pict) ", doc.Paragraphs[1].Text); // Spacer ones Assert.AreEqual("", doc.Paragraphs[2].Text); Assert.AreEqual("", doc.Paragraphs[3].Text); Assert.AreEqual("", doc.Paragraphs[4].Text); // Image one p = doc.Paragraphs[5]; Assert.AreEqual(6, p.Runs.Count); r = p.Runs[0]; Assert.AreEqual("", r.ToString()); Assert.AreEqual(1, r.GetEmbeddedPictures().Count); Assert.IsNotNull(r.GetEmbeddedPictures()[0].GetPictureData()); Assert.AreEqual("image1.wmf", r.GetEmbeddedPictures()[0].GetPictureData().FileName); r = p.Runs[1]; Assert.AreEqual("", r.ToString()); Assert.AreEqual(1, r.GetEmbeddedPictures().Count); Assert.IsNotNull(r.GetEmbeddedPictures()[0].GetPictureData()); Assert.AreEqual("image2.png", r.GetEmbeddedPictures()[0].GetPictureData().FileName); r = p.Runs[2]; Assert.AreEqual("", r.ToString()); Assert.AreEqual(1, r.GetEmbeddedPictures().Count); Assert.IsNotNull(r.GetEmbeddedPictures()[0].GetPictureData()); Assert.AreEqual("image3.emf", r.GetEmbeddedPictures()[0].GetPictureData().FileName); r = p.Runs[3]; Assert.AreEqual("", r.ToString()); Assert.AreEqual(1, r.GetEmbeddedPictures().Count); Assert.IsNotNull(r.GetEmbeddedPictures()[0].GetPictureData()); Assert.AreEqual("image4.emf", r.GetEmbeddedPictures()[0].GetPictureData().FileName); r = p.Runs[4]; Assert.AreEqual("", r.ToString()); Assert.AreEqual(1, r.GetEmbeddedPictures().Count); Assert.IsNotNull(r.GetEmbeddedPictures()[0].GetPictureData()); Assert.AreEqual("image5.jpeg", r.GetEmbeddedPictures()[0].GetPictureData().FileName); r = p.Runs[5]; //Is there a bug about XmlSerializer? it can not Deserialize the tag which inner text is only one whitespace //e.g. <w:t> </w:t> to CT_Text; //TODO Assert.AreEqual(" ", r.ToString()); Assert.AreEqual(0, r.GetEmbeddedPictures().Count); // Final spacer Assert.AreEqual("", doc.Paragraphs[(6)].Text); // Look in detail at one r = p.Runs[4]; XWPFPicture pict = r.GetEmbeddedPictures()[0]; //CT_Picture picture = pict.GetCTPicture(); NPOI.OpenXmlFormats.Dml.Picture.CT_Picture picture = pict.GetCTPicture(); //Assert.Fail("picture.blipFill.blip.embed is missing from wordprocessing CT_Picture."); Assert.AreEqual("rId8", picture.blipFill.blip.embed); // Ensure that the ooxml compiler Finds everything we need r.GetCTR().GetDrawingArray(0); r.GetCTR().GetDrawingArray(0).GetInlineArray(0); NPOI.OpenXmlFormats.Dml.CT_GraphicalObject go = r.GetCTR().GetDrawingArray(0).GetInlineArray(0).graphic; NPOI.OpenXmlFormats.Dml.CT_GraphicalObjectData god = r.GetCTR().GetDrawingArray(0).GetInlineArray(0).graphic.graphicData; //PicDocument pd = new PicDocumentImpl(null); //assertTrue(pd.isNil()); }
public void TestSettersGetters() { XWPFDocument doc = new XWPFDocument(); XWPFParagraph p = doc.CreateParagraph(); //Assert.IsTrue(p.IsEmpty); Assert.IsFalse(p.RemoveRun(0)); p.BorderTop = (/*setter*/ Borders.BabyPacifier); p.BorderBetween = (/*setter*/ Borders.BabyPacifier); p.BorderBottom = (/*setter*/ Borders.BabyPacifier); Assert.IsNotNull(p.IRuns); Assert.AreEqual(0, p.IRuns.Count); Assert.IsFalse(p.IsEmpty); Assert.IsNull(p.StyleID); Assert.IsNull(p.Style); Assert.IsNull(p.GetNumID()); p.SetNumID("12"); Assert.AreEqual("12", p.GetNumID()); p.SetNumID("13"); Assert.AreEqual("13", p.GetNumID()); Assert.IsNull(p.GetNumFmt()); //Assert.IsNull(p.GetNumIlvl()); Assert.AreEqual("", p.ParagraphText); Assert.AreEqual("", p.PictureText); Assert.AreEqual("", p.FootnoteText); p.BorderBetween = (/*setter*/ Borders.None); Assert.AreEqual(Borders.None, p.BorderBetween); p.BorderBetween = (/*setter*/ Borders.BasicBlackDashes); Assert.AreEqual(Borders.BasicBlackDashes, p.BorderBetween); p.BorderBottom = (/*setter*/ Borders.None); Assert.AreEqual(Borders.None, p.BorderBottom); p.BorderBottom = (/*setter*/ Borders.BabyPacifier); Assert.AreEqual(Borders.BabyPacifier, p.BorderBottom); p.BorderLeft = (/*setter*/ Borders.None); Assert.AreEqual(Borders.None, p.BorderLeft); p.BorderLeft = (/*setter*/ Borders.BasicWhiteSquares); Assert.AreEqual(Borders.BasicWhiteSquares, p.BorderLeft); p.BorderRight = (/*setter*/ Borders.None); Assert.AreEqual(Borders.None, p.BorderRight); p.BorderRight = (/*setter*/ Borders.BasicWhiteDashes); Assert.AreEqual(Borders.BasicWhiteDashes, p.BorderRight); p.BorderBottom = (/*setter*/ Borders.None); Assert.AreEqual(Borders.None, p.BorderBottom); p.BorderBottom = (/*setter*/ Borders.BasicWhiteDots); Assert.AreEqual(Borders.BasicWhiteDots, p.BorderBottom); Assert.IsFalse(p.IsPageBreak); p.IsPageBreak = (/*setter*/ true); Assert.IsTrue(p.IsPageBreak); p.IsPageBreak = (/*setter*/ false); Assert.IsFalse(p.IsPageBreak); Assert.AreEqual(-1, p.SpacingAfter); p.SpacingAfter = (/*setter*/ 12); Assert.AreEqual(12, p.SpacingAfter); Assert.AreEqual(-1, p.SpacingAfterLines); p.SpacingAfterLines = (/*setter*/ 14); Assert.AreEqual(14, p.SpacingAfterLines); Assert.AreEqual(-1, p.SpacingBefore); p.SpacingBefore = (/*setter*/ 16); Assert.AreEqual(16, p.SpacingBefore); Assert.AreEqual(-1, p.SpacingBeforeLines); p.SpacingBeforeLines = (/*setter*/ 18); Assert.AreEqual(18, p.SpacingBeforeLines); Assert.AreEqual(LineSpacingRule.AUTO, p.SpacingLineRule); p.SpacingLineRule = (/*setter*/ LineSpacingRule.EXACT); Assert.AreEqual(LineSpacingRule.EXACT, p.SpacingLineRule); Assert.AreEqual(-1, p.IndentationLeft); p.IndentationLeft = (/*setter*/ 21); Assert.AreEqual(21, p.IndentationLeft); Assert.AreEqual(-1, p.IndentationRight); p.IndentationRight = (/*setter*/ 25); Assert.AreEqual(25, p.IndentationRight); Assert.AreEqual(-1, p.IndentationHanging); p.IndentationHanging = (/*setter*/ 25); Assert.AreEqual(25, p.IndentationHanging); Assert.AreEqual(-1, p.IndentationFirstLine); p.IndentationFirstLine = (/*setter*/ 25); Assert.AreEqual(25, p.IndentationFirstLine); Assert.IsFalse(p.IsWordWrap); p.IsWordWrap = (/*setter*/ true); Assert.IsTrue(p.IsWordWrap); p.IsWordWrap = (/*setter*/ false); Assert.IsFalse(p.IsWordWrap); Assert.IsNull(p.Style); p.Style = (/*setter*/ "teststyle"); Assert.AreEqual("teststyle", p.Style); p.AddRun(new CT_R()); //Assert.IsTrue(p.RemoveRun(0)); Assert.IsNotNull(p.Body); Assert.AreEqual(BodyElementType.PARAGRAPH, p.ElementType); Assert.AreEqual(BodyType.DOCUMENT, p.PartType); }
private void verifyOneHeaderPicture(XWPFDocument sampleDoc) { XWPFHeaderFooterPolicy policy = sampleDoc.GetHeaderFooterPolicy(); XWPFHeader header = policy.GetDefaultHeader(); IList<XWPFPictureData> pictures = header.AllPictures; Assert.AreEqual(1, pictures.Count); }
static void Main(string[] args) { string filePath = Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory())) + @"\data\" + "Convert Word Doc to Other Formats.doc"; XWPFDocument wordDocument = new XWPFDocument(); FileStream out1 = new FileStream(filePath, FileMode.Open); using (FileStream sw = File.Create("Convert Word Doc to Other Formatsblank.docx")) { wordDocument.Write(sw); } }
static void Main(string[] args) { XWPFDocument doc = new XWPFDocument(); XWPFTable table = doc.CreateTable(3, 3); table.GetRow(1).GetCell(1).SetText("EXAMPLE OF TABLE"); XWPFParagraph p1 = doc.CreateParagraph(); XWPFRun r1 = p1.CreateRun(); r1.SetBold(true); r1.SetText("The quick brown fox"); r1.SetBold(true); r1.SetFontFamily("Courier"); r1.SetUnderline(UnderlinePatterns.DotDotDash); r1.SetTextPosition(100); table.GetRow(0).GetCell(0).SetParagraph(p1); table.GetRow(2).GetCell(2).SetText("only text"); FileStream out1 = new FileStream("simpleTable.docx", FileMode.Create); doc.Write(out1); out1.Close(); }