In HTML, the display:none property is used to hide table columns. When converting HTML to Word using Aspose.Words, the table styling becomes misaligned

Hello ,In HTML, the display:none property is used to hide table columns. When converting HTML to Word using Aspose.Words, the table styling becomes misaligned

Code is as follows

public byte[] htmlForByte(String downloadHtml,String docType,String pictureIdsJson,String processInstanceId,String[] pictureIds) {
		this.getLicense();
		Document doc = null;
		byte[] byteArray = null;
		ByteArrayOutputStream docout = null;
		try {
			doc = new Document();
			DocumentBuilder builder = new DocumentBuilder(doc);
			/**
			 * @author xcy 
			 * @date 2018.8.13
			 * 处理上传的封面图片和富文本中服务器路径格式图片在word导出中不显示问题
			 */
			//提取所有img标签字符串
			String docExporHtml=downloadHtml;
			Pattern pattern = Pattern.compile("<img.*?src=.*?>");
			Integer index= docExporHtml.indexOf("</style>");
			//style属性太长,将html整个数据从style分开,替换img是只替换html的body文件
			String prewContent=docExporHtml.substring(0, index);
			String nextContent= docExporHtml.substring(index,docExporHtml.length());
			Matcher matcher = pattern.matcher(nextContent);
			//找到所有src为服务器路径的img标签
			while(matcher.find()){
				String str=matcher.group(0);
				Integer strIndex= str.indexOf("src");
				String urlStr=str.substring(strIndex);
				if(urlStr.indexOf("data:image")==-1){
					Pattern pattern2 = Pattern.compile(".*?src=\".*?\"");
					Matcher matcher2 = pattern2.matcher(urlStr);
					while(matcher2.find()){
						String imgStr=matcher2.group(0);
						String src=imgStr.substring(5, imgStr.length()-1);
						//解决无法转换为服务器路径地址的图片(如.emf)截取图片信息报错问题
						if(imgStr.contains("file:///")){
							continue;
						}else if(imgStr.contains("getCoverImg")){
							//上传的图片封面的src格式和富文本的src格式不一样,分开判断
							String urlArray[]=imgStr.split("[?]");
							String params=urlArray[1];
							String paramsArray[]=params.split("=");
							String params1=paramsArray[1];
							String pictureArray[] = params1.split("\"");
							String pictureId = pictureArray[0];
							String imgSrcBase64=this.getCoverPictureFromOracle(pictureId);
							//将服务器路径替换为base64路径
							nextContent=nextContent.replace(src, imgSrcBase64);
						}else{
							String urlArray[]=imgStr.split("[?]");
							if(urlArray.length>1){
								String params=urlArray[1];
								String paramsArray[]=params.split("&");
								String ckDocType= paramsArray[0].substring(8);
								String ckPicId=paramsArray[1].split("\"")[0].substring(11);
								String[] ckPictureId=new String[1];
								ckPictureId[0]=ckPicId;
								//根据服务器路径返回base64格式的img路径
								Map<String, Object> map =this.getPictures(ckDocType, ckPictureId);
								String imgSrcBase64=ObjectUtils.toString(map.get(ckPicId));
								//将服务器路径替换为base64路径
								nextContent=nextContent.replace(src, imgSrcBase64);
							}else{
								ClassLoader classLoader = getClass().getClassLoader();
								String resourcePath = classLoader.getResource("").getPath();
								String rootPath = resourcePath.replaceAll("/WEB-INF/classes", "/design/image");
								File imgFile = new File(rootPath+"/zgsh.jpg");
								InputStream in = null;
								byte[] data = null;
								//读取图片字节数组
								
								try {
									in = new FileInputStream(imgFile);
									data = new byte[in.available()];
									in.read(data);
									in.close();
								} catch (IOException e) {
									e.printStackTrace();
								}
								Base64 base64 = new Base64();
								String encodeAsString ="data:image/jpg;base64,"+ base64.encodeAsString(data);
								//对字节数组Base64编码
//							Base64Encoder encoder = new Bas;
								nextContent=nextContent.replace(src, encodeAsString);
//							System.out.println(encodeAsString);
							}
						}
					}
				}
			}
			docExporHtml=prewContent+nextContent;
			//将替换img路径后的html插入到word转换
			builder.insertHtml(docExporHtml);		
			builder.moveToDocumentStart();
			builder.moveToBookmark("catalog");
			/**
			 * @author zn 
			 * @date 2022.1.12
			 * 目录重新换页
			 */
//		builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
			
			//目录层级,默认为2级,后续要做成参数配置
//		String catalogLevel= docXjsjWriteDao.getDocCatalogLevel(docType,"DOC_CATALOG_LEVEL");
			//目录层级,默认为2级,后续要做成参数配置
			String catalogLevel= docXjsjWriteDao.getDocCatalogLevel(docType,"DOC_CATALOG_LEVEL");
			String catalogFlag = "";
			if (StringUtils.isBlank(catalogLevel)){
				catalogLevel = "2";
			}
			if("1".equals(catalogLevel)){
				catalogFlag = " \\o \"1-1\" \\h \\z \\u ";
			}else if("2".equals(catalogLevel)){
				catalogFlag = " \\o \"1-2\" \\h \\z \\u ";
			}else if("3".equals(catalogLevel)){
				catalogFlag = " \\o \"1-3\" \\h \\z \\u ";
			}else{
				catalogFlag = "";
			}
			if(StringUtils.isNotEmpty(catalogFlag)){
				builder.insertHtml("<p align='center' style='font-size:18pt;font-family:宋体'>目录</p>");
				//根据文档章节标题生成目录数据
				builder.insertTableOfContents(catalogFlag);
				//获取二级目录的样式,并设置段落格式左缩进为0
//		doc.getStyles().getByStyleIdentifier(StyleIdentifier.TOC_2).getParagraphFormat().setLeftIndent(0);
				builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
				builder.getPageSetup().setSectionStart(1);
				builder.getPageSetup().setRestartPageNumbering(true);
//		moveToHeaderFooter 移动光标到页眉/页脚,再进行编辑操作
				builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
				builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
				builder.getFont().setSize(9);
				builder.getFont().setName("宋体");
				builder.insertField("Page");
				if(docType.equals("xjsj_zjgcsj")){
					setDocHeaderFooter(builder, "中国石化", docXjsjWriteDao.getJhbm(processInstanceId), "钻井工程设计");
				}
			}
			
			//设置文档保护,不允许修改
//			String docProtectIp = sysParamsService.getStringValue("DOC_PROTECT_IP");
			
//		builder.getFont().setName("宋体");
//        builder.getFont().setSize(12.0);
			doc.updateFields();
			
			Map<String, Object> map = this.getPictures(docType, pictureIds);
			JSONObject object = JSON.parseObject(pictureIdsJson);
			Set<String> set = object.keySet();
			Iterator<String> it = set.iterator();
			while (it.hasNext()) {
				String key = it.next();
				String pictureId = object.getString(key);
				Map<String, Object> m = this.getPictures(key, pictureId.split(","));
				map.putAll(m);
			}
			//将附图图片转换为流文件再输出到指定位置
			for (String key : map.keySet()) {
				String nameHtml = "<a name=\"" + key + "\"></a>";
				if (downloadHtml.indexOf(nameHtml) != -1) {
					builder.moveToBookmark(key);
					String str = ObjectUtils.toString(map.get(key));
					str = str.replaceAll("data:image/jpg;base64,", "");
					Base64 base64 = new Base64();
					byte[] baseByte = base64.decode(str);
					builder.insertImage(baseByte);
//				builder.insertImage(baseByte, 400, 300);
					builder.insertBreak(0);
				}
			}
			builder.getRowFormat().setHeadingFormat(true);
			setDocWidth(doc);
			docout = new ByteArrayOutputStream();
			doc.save(docout, SaveOptions.createSaveOptions(SaveFormat.DOC));
			byteArray= docout.toByteArray();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}finally{
			try {
				if(docout!=null){
					docout.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return byteArray;
	}
private void setDocWidth(Document doc) throws Exception {
		SectionCollection sections = doc.getSections();
		for (Section section : sections) {
			TableCollection tables = section.getBody().getTables();
			PageSetup pageSetup = section.getPageSetup();
			pageSetup.setLeftMargin(56.7);
			pageSetup.setRightMargin(56.7);
			for (Table table : tables) {
				//设置宽度百分比
//				table.setPreferredWidth(PreferredWidth.fromPercent(90));
				table.setPreferredWidth(PreferredWidth.fromPoints(483));
				table.setTextWrapping(TextWrapping.AROUND);
				table.setBottomPadding(0);
				table.setTopPadding(0);
//				table.setLeftPadding(0.566);
//				table.setRightPadding(0.566);
				table.setLeftPadding(0);
				table.setRightPadding(0);
				for (Row row : table.getRows()) {
					for (Cell cell : row.getCells()) {
//						cell.getCellFormat().setLeftPadding(0.566);
//						cell.getCellFormat().setRightPadding(0.566);
						cell.getCellFormat().setLeftPadding(0);
						cell.getCellFormat().setRightPadding(0);
						cell.getCellFormat().setBottomPadding(0);
						cell.getCellFormat().setTopPadding(0);
//						cell.getCellFormat().setFitText(true);

					}
					
				}
//				table.setAllowAutoFit(true);
//				table.setPreferredWidth(PreferredWidth.AUTO);
//				table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS);
//				table.setTextWrapping(0);
//				table.setAllowAutoFit(true);
//					table.autoFit(AutoFitBehavior.AUTO_FIT_TO_WINDOW);
			}
		}
//		PageSetup pageSetup = doc.getFirstSection().getPageSetup();
	}

@Mikeykiss

When converting HTML to Word using Aspose.Words, the display:none property in HTML can lead to misalignment issues in table styling, as Aspose.Words may not fully interpret hidden elements as intended.

To address this, consider the following approaches:

  1. Remove display:none: Preprocess the HTML to remove any elements with display:none before inserting it into the Word document. This ensures that all table columns are included in the conversion.

  2. Use Alternative CSS for Styling: Instead of relying on display:none, consider using CSS properties that maintain alignment without hiding elements. For example, you can use visibility:hidden or adjust the width of columns to achieve the desired layout.

  3. Debugging the Output: If the output remains misaligned, inspect the generated Word document to identify specific styling issues. Adjust the HTML or the insertion method accordingly.

Here’s a simple code snippet to preprocess the HTML by removing elements with display:none:

String processedHtml = downloadHtml.replaceAll("<[^>]*style=\"display:none;\"[^>]*>", "");
builder.insertHtml(processedHtml);

This approach helps ensure that all table columns are visible during the conversion process.

@Mikeykiss Could you please attach the problematic input HTML document? We will check it on our side and provide you more information. Unfortunately, it is impossible to analyze the problem using screenshots.

Thank you. I found out that it is html There is a problem

@Mikeykiss It is perfect that you managed to isolate the problem on your side.