/**************************************************************************************************** * Seletkov Ilya, iseletkov@gmail.com * ****************************************************************************************************/ /**************************************************************************************************** * This file contains class for reading and writing .docx files. All methods are based on docx4j * * library. * ****************************************************************************************************/ //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- CWordShell = function() { this.oOut = null; this.sPath = ""; this.sFile = ""; this.aTextStyles = new __map(); //Стили текста this.aParagraphStyles = new __map(); //Стили параграфов this.aCellStyles = new __map(); //Стили ячеек this.aBorderStyles = new __map(); //Стили границ таблиц this.oActivePart = null; //Часть документа, непосредственно с которой осуществляется работа this.oActiveSection = null; //Раздел документа (для основной части), в который осуществляется вывод //Список параграфов активной секции //Необходим для вывода титульной секции или секции ТОС this.aContents = new Array(); this.nSectionType = Constants.SECTION_DEFAULT; //this.oCoverSection = null; //Содержимое титульной секции //this.oTOCSection = null; this.oDefSectPr = null; this.oFactory = new org.docx4j.wml.ObjectFactory(); this.bTrue = new org.docx4j.wml.BooleanDefaultTrue(); this.bFalse = new org.docx4j.wml.BooleanDefaultTrue(); this.bFalse.setVal(false); //Путь для размещения временных файлов this.sTempPath = ""; this.aFooters = new __map(); //Запоминает футеры, которые выводились, чтобы можно было генерировать уникальные наименования частей this.aHeaders = new __map(); //Запоминает футеры, которые выводились, чтобы можно было генерировать уникальные наименования частей //Tables variables this.oTable = null; //Активная таблица, над которой выполняются команды TableCell this.nRow = 0; this.nColumn = 0; //Bookmarks for unique id; this.aBookmarks = new __map(); return; } //-------------------------------------------------------------------------------------------------- CWordShell.prototype.Init = function(sFile, oData) { if (!IsDefined(sFile)) sFile = getFileName("" + Context.getScriptInfo(Constants.SCRIPT_NAME) + ".docx"); this.sFile = sFile; //Папка для хранения промежуточных файлов var sPath = Context.getTempPath(); sPath+="\\temp\\"; var oFolder = java.io.File(sPath); //Если её нет - создаём if (!oFolder.exists()) oFolder.mkdirs(); this.sTempPath = sPath; //Результирующий объект с информацией, который будет записан в файл. if (!IsDefined(oData)) { this.oOut = org.docx4j.openpackaging.packages.WordprocessingMLPackage.createPackage(); } else { //Т.к. нет метода создания документа по массиву байт, //а есть только метод создания по входному потоку, //сохраним текущие данные в файл, и откроем его на чтение. //Сохраняем во временную папку текущие данные //Создаём файл var fileOut = java.io.File(this.sTempPath+"temp.docx"); fileOut.createNewFile(); //Получаем его поток var oOutStream = new java.io.FileOutputStream(fileOut); try { //Выводим данные в поток oOutStream.write(oData); //Закрываем поток oOutStream.close(); } catch (e) { } //Читаем всё содержимое файла в массив байт this.oOut = org.docx4j.openpackaging.packages.WordprocessingMLPackage.load(fileOut); } //Вывод информации будем осуществлять в основную часть документа this.oActivePart = this.oOut.getMainDocumentPart(); //this.oSectionContent = this.oActivePart.getContent(); this.aContents.push(this.oActivePart.getContent()); this.oMainContent = this.aContents[0]; //var sections = this.oOut.getDocumentModel().getSections(); this.oActiveSection = this.GetLastSection(); this.SetDistFooter(10); this.SetDistHeader(10); //Запоминаем настройки сраницы по умолчанию this.oDefSectPr = this.CreateSectPr(); this.CopySectPr(this.oActiveSection, this.oDefSectPr); this.oDefSectPr.getEGHdrFtrReferences().clear(); //Объекты с константами this.ParagraphAlignment = org.docx4j.wml.JcEnumeration; //this.Borders = org.apache.poi.xwpf.usermodel.Borders; //this.BreakType = org.apache.poi.xwpf.usermodel.BreakType; //this.BreakClear = org.apache.poi.xwpf.usermodel.BreakClear; //this.TextAlignment = org.apache.poi.xwpf.usermodel.TextAlignment; //this.UnderlinePatterns = org.apache.poi.xwpf.usermodel.UnderlinePatterns; //this.VerticalAlign = org.apache.poi.xwpf.usermodel.VerticalAlign; //this.LineSpacingRule = org.apache.poi.xwpf.usermodel.LineSpacingRule; //this.XWPFVertAlign = org.apache.poi.xwpf.usermodel.XWPFTableCell.XWPFVertAlign; //this.XWPFBorderType = org.apache.poi.xwpf.usermodel.XWPFTable.XWPFBorderType;*/ //Стили текста this.CreateTextStyle("Header12", "Times New Roman", 12, "000000", true, false); this.CreateTextStyle("Text12", "Times New Roman", 12, "000000", false, false); this.CreateTextStyle("Red12", "Times New Roman", 12, "FF0000", false, false); //Стили параграфов this.CreateParagraphStyle("TextCT", this.ParagraphAlignment.CENTER); this.SetParagraphStyleIndent("TextCT", 0,0,0); this.CreateParagraphStyle("TextLT", this.ParagraphAlignment.LEFT); this.SetParagraphStyleIndent("TextLT", 0,0,15); this.CreateParagraphStyle("TextRT", this.ParagraphAlignment.RIGHT); this.SetParagraphStyleIndent("TextRT", 0,0,0); this.CreateParagraphStyle("TextJT", this.ParagraphAlignment.BOTH); this.SetParagraphStyleIndent("TextJT", 0,0,15); this.CreateParagraphStyle("TextLT_NoInd", this.ParagraphAlignment.LEFT); this.SetParagraphStyleIndent("TextLT_NoInd", 0,0,0); this.CreateParagraphStyle("TextJT_NoInd", this.ParagraphAlignment.BOTH); this.SetParagraphStyleIndent("TextJT_NoInd", 0,0,0); //Styles of table and text borders this.CreateBorderStyle("BS", 4, org.docx4j.wml.STBorder.SINGLE, "000000"); this.CreateBorderStyle("THICK", 4, org.docx4j.wml.STBorder.THICK, "000000"); //Styles of cells in tables this.CreateCellStyle("Grey_BS_Top_Hor", null, "#"+__rgb(217, 217, 217), null, "BS", "BS", "BS", "BS"); this.CreateCellStyle("Grey_BS_Top_Vert", null, "#"+__rgb(217, 217, 217), "btLr", "BS", "BS", "BS", "BS"); this.CreateCellStyle("White_BS_Top_Hor", null, "#"+__rgb(255, 255, 255), null, "BS", "BS", "BS", "BS"); if (!IsDefined(oData)) { var stylesPart = new org.docx4j.openpackaging.parts.WordprocessingML.StyleDefinitionsPart(); stylesPart.unmarshalDefaultStyles(); this.oActivePart.addTargetPart(stylesPart); } return; } //-------------------------------------------------------------------------------------------------- //Text and paragraph styles //-------------------------------------------------------------------------------------------------- //Функция создаёт новый стиль текста CWordShell.prototype.CreateTextStyle = function(sName, sFont, nFontSize, sColor, bBold, bItalic) { var oRet = null; if (this.aTextStyles.ContainsKey(sName)) oRet = this.aTextStyles.Get(sName); else { oRet = new org.docx4j.wml.RPr(); this.aTextStyles.Insert(sName, oRet); } //Шрифт if (IsDefined(sFont)) { var RFonts = new org.docx4j.wml.RFonts(); // RFonts.setAscii(sFont); RFonts.setHAnsi(sFont); RFonts.setCs(sFont); oRet.setRFonts(RFonts); } //Жирность if (IsDefined(bBold)) { var oBDT = new org.docx4j.wml.BooleanDefaultTrue(); oBDT.setVal(bBold); oRet.setB(oBDT); } //Итальянец (курсив) if (IsDefined(bItalic)) { var oBDT = new org.docx4j.wml.BooleanDefaultTrue(); oBDT.setVal(bItalic); oRet.setI(oBDT); } //Размер if (IsDefined(nFontSize)) { var HpsMeasure = new org.docx4j.wml.HpsMeasure(); HpsMeasure.setVal(new java.math.BigInteger(2*nFontSize)); oRet.setSz(HpsMeasure); oRet.setSzCs(HpsMeasure); } if (IsDefined(sColor)) { var oColor = new org.docx4j.wml.Color(); oColor.setVal(sColor); oRet.setColor(oColor); } // if (IsDefined(nSubscribe)) // this.nSubscribe = nSubscribe; //Подстрочный/надстрочный/обычный return oRet; } //-------------------------------------------------------------------------------------------------- //Функция создаёт новый стиль параграфа CWordShell.prototype.CreateParagraphStyle = function(sName, nHAlignment, sColor, nTopBorder, nRightBorder, nBottomBorder, nLeftBorder) { var oRet; if (this.aParagraphStyles.ContainsKey(sName)) oRet = this.aParagraphStyles.Get(sName); else { oRet = new org.docx4j.wml.PPr(); this.aParagraphStyles.Insert(sName, oRet); } if (IsDefined(nHAlignment)) { var oJc = new org.docx4j.wml.Jc(); oJc.setVal(nHAlignment); oRet.setJc(oJc); } if (IsDefined(sColor)) { var oCTShd = this.oFactory.createCTShd(); //Fills parameters like word does for solid table cell underground. oCTShd.setVal(org.docx4j.wml.STShd.CLEAR); oCTShd.setColor("auto"); oCTShd.setFill(sColor); oRet.setShd(oCTShd); } //Отступ до и после абзаца = 0 //Надо по-другому - меняйте после создания var oSpacing = new org.docx4j.wml.PPrBase.Spacing(); oSpacing.setAfter(new java.math.BigInteger(0)); oSpacing.setBefore(new java.math.BigInteger(0)); oSpacing.setLine(new java.math.BigInteger(240)); //var oSpacingRule = new org.docx4j.wml.STLineSpacingRule(); oSpacing.setLineRule(org.docx4j.wml.STLineSpacingRule.AUTO); oRet.setSpacing(oSpacing); return oRet; } //-------------------------------------------------------------------------------------------------- //Функция устанавливает отступы для данного стиля параграфа CWordShell.prototype.SetParagraphStyleIndent = function(sName, nLeft, nRight, nFirst) { if (!this.aParagraphStyles.ContainsKey(sName)) return; var oInd = this.oFactory.createPPrBaseInd(); oInd.setFirstLine(new java.math.BigInteger(nFirst)); oInd.setLeft(new java.math.BigInteger(nLeft)); oInd.setRight(new java.math.BigInteger(nRight)); var oStyle = this.aParagraphStyles.Get(sName); oStyle.setInd(oInd); return; } //-------------------------------------------------------------------------------------------------- CWordShell.prototype.GetStylesByNames = function(sTextStyle, sParagraphStyle) { var oRet = new Object; oRet.oRPr = null; oRet.oPPr = null; //No styles provided if (!IsDefined(sTextStyle)) { oRet.oPPr = this.oFactory.createPPr(); oRet.oRPr = this.oFactory.createRPr(); } //Provided text style else { //Provided text and paragraph styles if (IsDefined(sParagraphStyle)) { if (this.aParagraphStyles.ContainsKey(sParagraphStyle)) oRet.oPPr = this.aParagraphStyles.Get(sParagraphStyle); else oRet.oPPr = this.oFactory.createPPr(); if (this.aTextStyles.ContainsKey(sTextStyle)) oRet.oRPr = this.aTextStyles.Get(sTextStyle); else oRet.oRPr = this.oFactory.createPPr(); } else //Provided word text style { var oStyle = this.GetStyleByName(sTextStyle); if (IsDefined(oStyle)) { oRet.oPPr = this.oFactory.createPPr(); var pStyle = this.oFactory.createPPrBasePStyle(); oRet.oPPr.setPStyle(pStyle); pStyle.setVal(oStyle.getStyleId()); oRet.oRPr = oStyle.getRPr(); } else { oRet.oPPr = this.oFactory.createPPr(); oRet.oRPr = this.oFactory.createRPr(); } } } return oRet; } //-------------------------------------------------------------------------------------------------- //Function return word style by provided name (in english) CWordShell.prototype.GetStyleByName = function(sStyleName) { var aStyles = this.oActivePart.getStyleDefinitionsPart().getJaxbElement().getStyle(); for (var i=0; inH) oLV.pageSize.setOrient(org.docx4j.wml.STPageOrientation.LANDSCAPE); else oLV.pageSize.setOrient(org.docx4j.wml.STPageOrientation.PORTRAIT); //Sets the code of paper format oLV.pageSize.setCode(new java.math.BigInteger(oLV.nCode)); this.oActiveSection.setPgSz(oLV.pageSize); return; } //-------------------------------------------------------------------------------------------------- //Задаёт ширину страниц CWordShell.prototype.SetPageWidth = function(nW) { //Переводим из милиметров в ТВИПы. ТВИП - типографическая единица, равная 1/20 пункта. nW = parseInt(nW*56.7); var nIW = new java.math.BigInteger(nW); var pageSize = this.oActiveSection.getPgSz(); //Структура с размерами страницы и полей pageSize.setW(nIW); this.oActiveSection.setPgSz(pageSize); return; } //-------------------------------------------------------------------------------------------------- //Задаёт ширину страниц CWordShell.prototype.SetPageHeight = function(nH) { //Переводим из милиметров в ТВИПы. ТВИП - типографическая единица, равная 1/20 пункта. nH = parseInt(nH*56.7); var nIH = new java.math.BigInteger(nH); var pageSize = this.oActiveSection.getPgSz(); //Структура с размерами страницы и полей pageSize.setH(nIH); this.oActiveSection.setPgSz(pageSize); return; } //-------------------------------------------------------------------------------------------------- CWordShell.prototype.GetPageWidth = function() { var PgSz = this.oActiveSection.getPgSz(); return parseInt(PgSz.getW()/56.7); } //-------------------------------------------------------------------------------------------------- CWordShell.prototype.GetPageHeight = function() { var PgSz = this.oActiveSection.getPgSz(); return parseInt(PgSz.getH()/56.7); } //-------------------------------------------------------------------------------------------------- CWordShell.prototype.GetLeftMargin = function() { var PgMar = this.oActiveSection.getPgMar(); return parseInt(PgMar.getLeft()/56.7); } //-------------------------------------------------------------------------------------------------- CWordShell.prototype.GetTopMargin = function() { var PgMar = this.oActiveSection.getPgMar(); return parseInt(PgMar.getTop()/56.7); } //-------------------------------------------------------------------------------------------------- CWordShell.prototype.GetRightMargin = function() { var PgMar = this.oActiveSection.getPgMar(); return parseInt(PgMar.getRight()/56.7); } //-------------------------------------------------------------------------------------------------- CWordShell.prototype.GetBottomMargin = function() { var PgMar = this.oActiveSection.getPgMar(); return parseInt(PgMar.getBottom()/56.7); } //-------------------------------------------------------------------------------------------------- CWordShell.prototype.GetDistFooter = function() { var PgMar = this.oActiveSection.getPgMar(); return parseInt(PgMar.getFooter()/56.7); } //-------------------------------------------------------------------------------------------------- CWordShell.prototype.GetDistHeader = function() { var PgMar = this.oActiveSection.getPgMar(); return parseInt(PgMar.getHeader()/56.7); } //-------------------------------------------------------------------------------------------------- CWordShell.prototype.SetLeftMargin = function(val) { var PgMar = this.oActiveSection.getPgMar(); return PgMar.setLeft(new java.math.BigInteger(parseInt(val*56.7))); } //-------------------------------------------------------------------------------------------------- CWordShell.prototype.SetTopMargin = function(val) { var PgMar = this.oActiveSection.getPgMar(); return PgMar.setTop(new java.math.BigInteger(parseInt(val*56.7))); } //-------------------------------------------------------------------------------------------------- CWordShell.prototype.SetRightMargin = function(val) { var PgMar = this.oActiveSection.getPgMar(); return PgMar.setRight(new java.math.BigInteger(parseInt(val*56.7))); } //-------------------------------------------------------------------------------------------------- CWordShell.prototype.SetBottomMargin = function(val) { var PgMar = this.oActiveSection.getPgMar(); return PgMar.setBottom(new java.math.BigInteger(parseInt(val*56.7))); } //-------------------------------------------------------------------------------------------------- CWordShell.prototype.SetDistFooter = function(val) { var PgMar = this.oActiveSection.getPgMar(); return PgMar.setFooter(new java.math.BigInteger(parseInt(val*56.7))); } //-------------------------------------------------------------------------------------------------- CWordShell.prototype.SetDistHeader = function(val) { var PgMar = this.oActiveSection.getPgMar(); return PgMar.setHeader(new java.math.BigInteger(parseInt(val*56.7))); } //-------------------------------------------------------------------------------------------------- CWordShell.prototype.GetClientWidth = function() { var nWidth = this.GetPageWidth()-this.GetLeftMargin()-this.GetRightMargin(); return nWidth; } //-------------------------------------------------------------------------------------------------- CWordShell.prototype.GetClientHeight = function() { var nHeight = oWord.GetPageHeight(); if (MO.bColonticuls) nHeight = nHeight-oWord.GetDistFooter()-oWord.GetDistHeader(); else nHeight = nHeight-oWord.GetTopMargin()-oWord.GetBottomMargin(); return nHeight; } //-------------------------------------------------------------------------------------------------- //Function replaces entries of text sFrom in all cells of oTable by sTo text. CWordShell.prototype.GetJAXBElementValue = function(oElement) { if (oElement["class"] == "class javax.xml.bind.JAXBElement") return oElement.getValue(); return oElement; } //-------------------------------------------------------------------------------------------------- //Find and replace //-------------------------------------------------------------------------------------------------- //Function replaces all entries of text sFrom by text sTo in current document. CWordShell.prototype.ReplaceText = function(sFrom, sTo) { //for all parts in document var aParts = this.oOut.getParts().getParts().values(); var oIterator = aParts.iterator(); while (oIterator.hasNext()) { var oPart = oIterator.next(); var sClass = oPart["class"]; var oContent; //Choose only parts of document containing visible text. if (sClass == "class org.docx4j.openpackaging.parts.WordprocessingML.FooterPart") oContent = oPart.getContent(); if (sClass == "class org.docx4j.openpackaging.parts.WordprocessingML.HeaderPart") oContent = oPart.getContent(); if (sClass == "class org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart") oContent = oPart.getContent(); if (!IsDefined(oContent)) continue; //For all paragraphs in content for (var i=0; i=0) { //replace it by sTo text sText = sText.replace(sFrom,sTo); //Change the text of first run containing sFrom text (or it's first part) oR = oP.getContent().get(j); oR = this.GetJAXBElementValue(oR); if (oR["class"]!= "class org.docx4j.wml.R") { oR = this.oFactory.createR(); //if first element is not run //add new run after first element, put new text into it oP.getContent().add(j+1, oR); //marks, that there is one more element in paragraph j++; k++; } var oText = new org.docx4j.wml.Text(); oText.setValue(sText); oR.getContent().clear(); oR.getContent().add(oText); //deletes all runs, which early contains parts of sFrom for (var l=j+1; l=0) { oLV.oRet = new Object; oLV.oRet.oContent = oLV.oContent; oLV.oRet.nPos = i; delete oLV.aParts; return oLV.oRet; } } if (oP["class"] == "class org.docx4j.wml.Tbl") { oLV.oRet = this.FindTableText(oP, sFindText); if (IsDefined(oLV.oRet)) { delete oLV.aParts; return oLV.oRet; } } } } delete oLV.aParts; return null; } //-------------------------------------------------------------------------------------------------- //Function replaces entries of text sFrom in all cells of oTable by sTo text. CWordShell.prototype.FindTableText = function(oTable, sFindText) { var oLV = new Object; //In tables we have to look in all cells oTable = this.GetJAXBElementValue(oTable); if (oTable["class"] != "class org.docx4j.wml.Tbl") return false; oLV.aRows = oTable.getEGContentRowContent(); //For all rows in table for (var j=0; j=0) { oLV.oRet = new Object; oLV.oRet.oContent = oLV.oContent; oLV.oRet.nPos = l; return oLV.oRet; } } } } } return null; } //-------------------------------------------------------------------------------------------------- //Headers and Footers //-------------------------------------------------------------------------------------------------- //Функция создаёт верхний колонтитул в документе CWordShell.prototype.BeginHeader = function() { var oPartName = new org.docx4j.openpackaging.parts.PartName("/word/header"+this.aHeaders.mapcontents.length+".xml"); var oPart = new org.docx4j.openpackaging.parts.WordprocessingML.HeaderPart(oPartName); this.aFooters.Insert(oPartName, oPart); oPart.setPackage(this.oOut); var oHeader = this.oFactory.createHdr(); oPart.setJaxbElement(oHeader); this.oActivePart = oPart; this.aContents.push(oPart.getContent()); return oPart; } //-------------------------------------------------------------------------------------------------- //Функция завершает создание верхнего колонтитула в документе CWordShell.prototype.EndHeader = function() { var relation = this.oOut.getMainDocumentPart().addTargetPart(this.oActivePart); this.CreateHeaderReference(relation); this.oActivePart = this.oOut.getMainDocumentPart(); this.aContents.pop(); return; } //-------------------------------------------------------------------------------------------------- //Добавляет ссылку (какую? зачем?) в активный раздел документа CWordShell.prototype.CreateHeaderReference = function(relation) { var headerReference = this.oFactory.createHeaderReference(); headerReference.setId(relation.getId()); headerReference.setType(org.docx4j.wml.HdrFtrRef.DEFAULT); var aRefs = this.oActiveSection.getEGHdrFtrReferences();//.clear(); for (var i=0; i" + "" + "" + "" + ""; var tblPr = tblPr = org.docx4j.XmlUtils.unmarshalString(strTblPr); this.oTable.setTblPr(tblPr); var tblGrid = this.oFactory.createTblGrid(); this.oTable.setTblGrid(tblGrid); var nWidth; var gridCol; var nTableWidth = this.GetClientWidth()*nWidthPercent/100; //Добавляем в сетку колонки, задаём им ширину var aCols = tblGrid.getGridCol(); for (var i=0; iaRows.size()-1) return; var oRow = this.GetJAXBElementValue(aRows.get(nRow)); //Ячейки с таким номером в строчке не существует var aCells = oRow.getEGContentCellContent(); if (nColumn <0 || nColumn>aCells.size()) return; var oCell; var aCols = this.oTable.getTblGrid().getGridCol(); //Новая ячейка в конце строчки if (nColumn==aCells.size()) { //Проверим наличие колонки слева if (aCols.size()<=nColumn) { return; } oCell = this.oFactory.createTc(); aCells.add(oCell); if (IsDefined(sCellStyle)) this.TableCellStyle(oCell, sCellStyle); else this.TableCellBorders(oCell, "THICK", "THICK", "THICK", "THICK"); } else { oCell = this.GetJAXBElementValue(aCells.get(nColumn)); } oLV.oColumn = aCols.get(nColumn); oLV.tcPr = oCell.getTcPr(); if (!IsDefined(oLV.tcPr)) { oLV.tcPr = this.oFactory.createTcPr(); oCell.setTcPr(oLV.tcPr); } //oCell.setTcPr(tcPr); // oLV.cellWidth = this.oFactory.createTblWidth(); oLV.tcPr.setTcW(oLV.cellWidth); oLV.cellWidth.setType("dxa"); oLV.cellWidth.setW(oLV.oColumn.getW()); //Содержимое ячейки oLV.oPragraph = this.CreateParagraph(sText, sTextStyle, sParagraphStyle); oCell.getEGBlockLevelElts().add(oLV.oPragraph); return oCell; } //-------------------------------------------------------------------------------------------------- //В активную таблицу в последнюю строчку добавляет ячейку CWordShell.prototype.TableCellF = function(sText, sTextStyle, sParagraphStyle, sCellStyle) { var oCell = this.TableCellIndF(this.nRow-1, this.nColumn, sText, sTextStyle, sParagraphStyle, sCellStyle); this.nColumn++; return oCell; } //-------------------------------------------------------------------------------------------------- //Создаёт нужное количество ячеек и объединяет их CWordShell.prototype.TableCellMergeF = function(sText, nRowSpan, nColSpan, sTextStyle, sParagraphStyle, sCellStyle) { //Создаём первую ячейку var oCell = this.TableCellIndF(this.nRow-1, this.nColumn, sText, sTextStyle, sParagraphStyle, sCellStyle); //Рассчитываем новую ширину var aCols = this.oTable.getTblGrid().getGridCol(); var nWidth = 0; for (var i=this.nColumn; ioLV.aRows.size()-1) return; oLV.oRow = oLV.aRows.get(nRow); //Ячейки с таким номером в строчке не существует oLV.aCells = oLV.oRow.getEGContentCellContent(); if (nColumn <0 || nColumn>oLV.aCells.size()-1) return; oLV.oCell = oLV.aCells.get(nColumn); this.TableCellBorders(oLV.oCell, sLeft, sTop, sRight, sBottom); return; } //-------------------------------------------------------------------------------------------------- //В активной таблице в укзанной ячейке изменяются параметры границ //в соответствии с указанными стилями CWordShell.prototype.TableCellBorders = function(oCell, sLeft, sTop, sRight, sBottom) { var oLV = new Object; oLV.tcPr = oCell.getTcPr(); if (!IsDefined(oLV.tcPr)) { oLV.tcPr = this.oFactory.createTcPr(); oCell.setTcPr(oLV.tcPr); } oLV.tcBorders = oLV.tcPr.getTcBorders(); if (!IsDefined(oLV.tcBorders)) { oLV.tcBorders = this.oFactory.createTcPrInnerTcBorders(); oLV.tcPr.setTcBorders(oLV.tcBorders); } if (this.aBorderStyles.ContainsKey(sLeft)) oLV.tcBorders.setLeft(this.aBorderStyles.Get(sLeft)); if (this.aBorderStyles.ContainsKey(sTop)) oLV.tcBorders.setTop(this.aBorderStyles.Get(sTop)); if (this.aBorderStyles.ContainsKey(sRight)) oLV.tcBorders.setRight(this.aBorderStyles.Get(sRight)); if (this.aBorderStyles.ContainsKey(sBottom)) oLV.tcBorders.setBottom(this.aBorderStyles.Get(sBottom)); return; } //-------------------------------------------------------------------------------------------------- //Функция создаёт новый стиль ячейки CWordShell.prototype.CreateCellStyle = function(sName, nVAlignment, sColor, sDirection, sTopBorder, sRightBorder, sBottomBorder, sLeftBorder) { var oRet; var oLV = new Object; if (this.aCellStyles.ContainsKey(sName)) oRet = this.aCellStyles.Get(sName); else { oRet = this.oFactory.createTcPr(); this.aCellStyles.Insert(sName, oRet); } //Vertical alignment of all paragraphs in the cell if (IsDefined(nVAlignment)) { oLV.oCTVerticalJc = this.oFactory.createCTVerticalJc(); oLV.oCTVerticalJc.setVal(nVAlignment); oRet.setVAlignment(oLV.oCTVerticalJc); } if (IsDefined(sColor)) { oLV.oCTShd = this.oFactory.createCTShd(); //Fills parameters like word does for solid table cell underground. oLV.oCTShd.setVal(org.docx4j.wml.STShd.CLEAR); oLV.oCTShd.setColor("auto"); oLV.oCTShd.setFill(sColor); oRet.setShd(oLV.oCTShd); } if (IsDefined(sDirection)) { oLV.oTextDirection = this.oFactory.createTextDirection(); oLV.oTextDirection.setVal(sDirection); oRet.setTextDirection(oLV.oTextDirection); } oLV.oTcBorders = this.oFactory.createTcPrInnerTcBorders(); if (this.aBorderStyles.ContainsKey(sLeftBorder)) oLV.oTcBorders.setLeft(this.aBorderStyles.Get(sLeftBorder)); if (this.aBorderStyles.ContainsKey(sTopBorder)) oLV.oTcBorders.setTop(this.aBorderStyles.Get(sTopBorder)); if (this.aBorderStyles.ContainsKey(sRightBorder)) oLV.oTcBorders.setRight(this.aBorderStyles.Get(sRightBorder)); if (this.aBorderStyles.ContainsKey(sBottomBorder)) oLV.oTcBorders.setBottom(this.aBorderStyles.Get(sBottomBorder)); oRet.setTcBorders(oLV.oTcBorders); return oRet; } //-------------------------------------------------------------------------------------------------- //В активной таблице в укзанной ячейке изменяются параметры границ //в соответствии с указанными стилями CWordShell.prototype.TableCellStyle = function(oCell, sStyle) { if (!this.aCellStyles.ContainsKey(sStyle)) return; oCell.setTcPr(this.aCellStyles.Get(sStyle)); return; } //-------------------------------------------------------------------------------------------------- //Returns list of tables in document as java.util.Vector CWordShell.prototype.TablesList = function() { //for all parts in document var aParts = this.oOut.getParts().getParts().values(); var oIterator = aParts.iterator(); var aRet = new java.util.Vector(); while (oIterator.hasNext()) { var oPart = oIterator.next(); var sClass = oPart["class"]; var oContent; //Choose only parts of document containing visible text. if (sClass == "class org.docx4j.openpackaging.parts.WordprocessingML.FooterPart") oContent = oPart.getContent(); if (sClass == "class org.docx4j.openpackaging.parts.WordprocessingML.HeaderPart") oContent = oPart.getContent(); if (sClass == "class org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart") oContent = oPart.getContent(); if (!IsDefined(oContent)) continue; //For all paragraphs in content for (var i=0; i0) { //Проверяем тип последнего элемента в списке элементов var oLastPar =this.aContents[0].get(this.aContents[0].size()-1); if (oLastPar["class"]=="class org.docx4j.wml.P") if (IsDefined(oLastPar.getPPr())) oSectPr = oLastPar.getPPr().getSectPr(); //Если в последнем элементе не присутствует разделитель разделов if (!IsDefined(oSectPr)) { //Вставляем новый разрыв разделов oSectPr = this.AddSectPr(); //Переносим в него настройки последней части документа this.CopySectPr(this.oActiveSection, oSectPr); this.oOut.getDocumentModel().refresh(); //Для последней части документа устанавливаем стандартные настройки if (!bCopyProperties) { var lastSectPr = this.GetLastSection(); this.CopySectPr(this.oDefSectPr, lastSectPr); this.BeginHeader(); this.OutputLn(""); this.EndHeader(); this.BeginFooter(); this.OutputLn(""); this.EndFooter(); } } } else //Вообще нет никаких элементов ещё - берём за основу единственную секцию oSectPr = this.oActiveSection; //Создаём завершающий раздел для новой секции, но пока не вставляем this.oActiveSection = this.CreateSectPr(); if (bCopyProperties) { this.CopySectPr(oSectPr, this.oActiveSection); } else { this.CopySectPr(this.oDefSectPr, this.oActiveSection); this.BeginHeader(); this.OutputLn(""); this.EndHeader(); this.BeginFooter(); this.OutputLn(""); this.EndFooter(); } //Список параграфов секции - пока пустой this.aContents.push(new java.util.Vector()); this.oActiveSection.setTitlePg(this.bFalse); break; } return; } //-------------------------------------------------------------------------------------------------- //Fnction copies header data from previous section to active section //And doesnt set word flag "like in previous section". //This means that both headers look the same but are independent. /*CWordShell.prototype.CopyHeader = function() { //Find footer to change var aSections = oWord.oOut.getDocumentModel().getSections(); var oSectionWrapper = aSections.get(aSections.size()-1); var oFooter = oSectionWrapper.getHeaderFooterPolicy().getOddFooter(); //Картинку нужно добавить в начало oWord.BeginFooter(); oWord.OutputLnF("","Text12","TextRT"); oWord.OutGraphic(oLogoPict, -1, nZoom*nW, nZoom*nH); //Footer exists in the document if (IsDefined(oFooter)) { var oOldContent = oFooter.getContent(); oWord.aContents[oWord.aContents.length-1].addAll(oOldContent); } oWord.EndFooter(); }*/ //-------------------------------------------------------------------------------------------------- //Здесь в переменную oActiveSection запоминаем последнюю секцию в документе CWordShell.prototype.EndSection = function() { if (this.aContents.length!=2) { Dialogs.MsgBox("Ошибка: некорретное соответствие открытий и закрытий разделов или колонтитулов!"); return; //Ошибка: секция в секции или лишние закрытия частей } //-------------------- //Переносим содержимое секции в основную часть документа) //var oMainContent = this.oOut.getMainDocumentPart().getContent(); for (var i=0; i100)) //Если маштаб не корректный или увеличивающий - не изменяем размер { nZoom=100; } //var oFile; if (oPicture["class"]=="class string") sFile = ""+oPicture; if ((oPicture["class"]=="class com.idsscheer.aris.server.bl.common.reportobjects.aris.logic.AModelPicture")|| (oPicture["class"]=="class com.idsscheer.report.output.external.interfaces.impl.ABitmapPicture")) { //Напрямую массив байт из объекта Picture не получается взять, так как нет метода для этого //Зато есть метод сохранить в файл sFile = this.sTempPath+"\\TempGraphic.png"; oPicture.Save(sFile); } if (sFile.length==0) return; oLV.oFile = new java.io.File(sFile); if (!oLV.oFile.exists()) return; //СОздаём изображение из массива байт oLV.imagePart = org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage.createImagePart(this.oOut, this.oActivePart, oLV.oFile); var is = javax.imageio.ImageIO.createImageInputStream(oLV.oFile); oLV.aReaders = javax.imageio.ImageIO.getImageReadersByFormatName("png"); if (oLV.aReaders.hasNext()) { oLV.oImageReader = oLV.aReaders.next(); oLV.oImageReader.setInput(is); var nImX = oLV.oImageReader.getWidth(0)*0.217; var nImY = oLV.oImageReader.getHeight(0)*0.217; } else return; if (nZoom==-1) { //Если необходимо автоматически изменить размер, посмотрим, какая должна быть ширина рисунка //У нас указаны максимальные размеры, найдём масштабирующие коэффициенты var kX = dx/nImX; //Масштабирующие коэффициенты, чтобы подогнать под запрашиваемые размеры var kY = dy/nImY; //Выберем тот коэффициент, который сильнее уменьшает изображение if (kX0) oLV.p = oLV.oContent.get(oLV.oContent.size()-1); else { //Если абзацев ещё нет - создадим новый oLV.p = this.oFactory.createP(); oLV.oContent.add(oLV.p); } oLV.run = this.oFactory.createR(); oLV.p.getContent().add(oLV.run); oLV.run.getContent().add(oLV.drawing); return; } //-------------------------------------------------------------------------------------------------- //TOC and bookmarks //-------------------------------------------------------------------------------------------------- //Функция выводит поле содержание в активную часть документа CWordShell.prototype.OutputTOC = function() { var oP = this.oFactory.createP(); var oR = this.oFactory.createR(); var fldchar = this.oFactory.createFldChar(); fldchar.setFldCharType(org.docx4j.wml.STFldCharType.BEGIN); fldchar.setDirty(true); oR.getContent().add(getWrappedFldChar(fldchar)); oP.getContent().add(oR); oR = this.oFactory.createR(); oText = new org.docx4j.wml.Text(); oText.setSpace("preserve"); oText.setValue("TOC \\o \"1-3\" \\h \\z \\u \\h"); oR.getContent().add(this.oFactory.createRInstrText(oText)); oP.getContent().add(oR); var fldcharend = this.oFactory.createFldChar(); fldcharend.setFldCharType(org.docx4j.wml.STFldCharType.END); oR = this.oFactory.createR(); oR.getContent().add(getWrappedFldChar(fldcharend)); oP.getContent().add(oR); this.aContents[this.aContents.length-1].add(oP); return; function getWrappedFldChar(fldchar) { var QName = new javax.xml.namespace.QName(javax.xml.namespace.Namespaces.NS_WORD12, "fldChar"); return new javax.xml.bind.JAXBElement(QName, org.docx4j.wml.FldChar, fldchar); } } //-------------------------------------------------------------------------------------------------- //Function creates paragraph with bookmark and run in it. var BOOKMARK_TYPE_DEFAULT = 1; var BOOKMARK_TYPE_TOC = 2; CWordShell.prototype.OutputBookmarkF = function(sText, nType, sTextStyle, sParagraphStyle) { var oP = this.oFactory.createP(); var oStyleObj = this.GetStylesByNames(sTextStyle, sParagraphStyle); oP.setPPr(oStyleObj.oPPr); //id for BM var nBMID = this.GetNewBookmarkID(); //List of BMs of the same type if (this.aBookmarks.ContainsKey(nType)) var aBMList = this.aBookmarks.Get(nType); else { var aBMList = new __map(); this.aBookmarks.Insert(nType, aBMList); } //Generate unique name for BM var sName = "000000001"; switch(nType) { case BOOKMARK_TYPE_TOC: { sName = "_Toc"+swfillLongTo(this.aBookmarks.Get(nType).mapcontents.length, 9); break; } default: { sName = swfillLongTo(this.aBookmarks.Get(BOOKMARK_TYPE_DEFAULT).mapcontents.length, 9); break; } } //bookmark start var oBM = this.oFactory.createCTBookmark(); oBM.setId(nBMID); oBM.setName(sName); var oBMStart = this.oFactory.createBodyBookmarkStart(oBM); oP.getContent().add(oBMStart); //Add bookmarkcontent var run = this.oFactory.createR(); var text = new org.docx4j.wml.Text(); text.setValue(sText); run.getContent().add(text); oP.getContent().add(run); // Add bookmark end var mr = this.oFactory.createCTMarkupRange(); mr.setId(nBMID); var oBMEnd = this.oFactory.createBodyBookmarkEnd(mr); oP.getContent().add(oBMEnd); //Add paragraph to active content this.aContents[this.aContents.length-1].add(oP); return; } //-------------------------------------------------------------------------------------------------- //function creates unique id for bookmark CWordShell.prototype.GetNewBookmarkID = function() { var nCount = 1; for (var i=0; i0) { var oLastPar =this.aContents[0].get(this.aContents[0].size()-1); //У параграфа для разрыва раздела содержание отсутствует if (oLastPar.getContent().size()==0) //Содержание отсутсвует if (IsDefined(oLastPar.getPPr())) if (IsDefined(oLastPar.getPPr().getSectPr())) { //this.CopySectPr(oLastPar.getPPr().getSectPr(), this.oActiveSection); //Удалим лишний разделитель this.aContents[0].remove(this.aContents[0].size()-1); } } //Файл сохраняем во временную папку в специальной папке сервера //Создаём файл var fileOut = new java.io.File(this.sTempPath+this.sFile); this.oOut.save(fileOut); //Открываем файл на чтение var oInputStream = new java.io.FileInputStream(fileOut); //Читаем всё содержимое файла в массив байт var bytes = org.apache.commons.io.IOUtils.toByteArray(oInputStream); oInputStream.close(); //По массиву байт и названию АРИС создаёт новый файл, который затем будет перемещён клиенту Context.addOutputFile(this.sFile, bytes); //Удаляем временный файл var ret = fileOut["delete"](); return; }