JavaScript打印Excel、Word

JavaScript打印Excel、WordJavaScript调用本地打印机,打印Excel、Word文件之前写过一篇文章,使用java调用打印机打印Excel文件:java调用打印机:http://blog.csdn.net/wangxiaoan1234/article/details/75116072但是java运行与服务器上,外部访问无法调用本地打印机。

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全家桶1年46,售后保障稳定

JavaScript调用本地打印机,打印Excel、Word文件


之前写过一篇文章,使用java调用打印机打印Excel文件:
java调用打印机:http://blog.csdn.net/wangxiaoan1234/article/details/76032280
但是java运行与服务器上,外部访问无法调用本地打印机。
假设项目需求为:点击按钮打印某个报表(Excel)。当项目发布到服务器上后,当使用java调用打印机,无论哪台电脑访问页面,点击打印按钮,调用的都是java所运行的服务器上的打印机。

理想:

Created with Raphaël 2.1.0 用户 用户 服务器 服务器 我要打印报表 收到请求,调用打印程序 弄好了,你打印吧 调用打印机,打印报表

实际:

Created with Raphaël 2.1.0 用户 用户 服务器 服务器 我要打印报表 收到请求,调用打印程序 怎么调用了我自己的打印机,是java的锅,我不背 很抱歉,报表在我这打印好了,你过来取吧! 你大爷的!

解决思路:
JavaScript运行在本地,使用JavaScript调用本地打印机。

想到可行方法:

  • 直接调用打印机打印本地文件(IE浏览器用此方法)。
  • java后台将Excel转换成html页面,调用window.print()函数打印整个页面(通用);
  • 安装打印插件(麻烦)

使用Spring poi将Excel、Word转换为html再进行打印的好处有:

  1. 所有浏览器通用
  2. 可以进行打印预览
  3. 可视化的打印参数设置
  4. 我不会别的o(╯□╰)o

IE浏览器直接调用打印机(无预览):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>打印测试</title>
</head>
<body>
    <input id="btnPrint" value="打印整个页面" type="button" onclick="btnPrintClick()"/>  
    <input id="btnPrintExcel" value="打印Excel" type="button" onclick="printExcel('D:/test.xlsx')"/> 
    <script> //调用浏览器的打印功能  function btnPrintClick(){ 
     window.print(); } //打印Excel function printExcel(obj) { 
     var explorer = window.navigator.userAgent ; if (explorer.indexOf("MSIE") >= 0 || "ActiveXObject" in window) { //判断是否为ie浏览器 var xlsApp = null; try { xlsApp = new ActiveXObject('Excel.Application'); } catch(e) { alert(e + ', 原因分析: 浏览器安全级别较高导致不能创建Excel对象或者客户端没有安装Excel软件'); return; } var xlBook = xlsApp.Workbooks.Open(obj); var xlsheet = xlBook.Worksheets(1); xlsApp.Application.Visible = false; xlsApp.visible = false; xlsheet.Printout; xlsApp.Quit(); xlsApp=null; } else { alert("只支持IE浏览器"); } } </script>
</body>
</html>

Jetbrains全家桶1年46,售后保障稳定


Java将Excel解析成html,在该页面上调用window.print()打印页面:

maven依赖:

<!-- POI -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.16</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.lucee/curvesapi -->
        <dependency>
            <groupId>org.lucee</groupId>
            <artifactId>curvesapi</artifactId>
            <version>1.04.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans -->
        <dependency>
            <groupId>org.apache.xmlbeans</groupId>
            <artifactId>xmlbeans</artifactId>
            <version>2.6.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>3.16</version>
        </dependency>

jar包下载地址:http://download.csdn.net/detail/wangxiaoan1234/9909138

后台Excel转换HTML类:
类文件下载地址:http://download.csdn.net/detail/wangxiaoan1234/9909123

package com.srie.util.excel;

import org.apache.poi.hssf.converter.ExcelToHtmlConverter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;

/** * 利用POI将Excel2003转换为HTML(不能读取图片并且不支持Excel2007) */
public class PoiExcel03lToHtml { 
   

    /** * 程序入口方法 * @param excelPath 待读取的Excel路径 * @param htmlPath 转换生成的HTML输出路径 */
    public static void convertExcelToHtml(String excelPath, String htmlPath) {
        File excelFile = new File(excelPath);
        File htmlFile = new File(htmlPath);
        File htmlFolder = htmlFile.getParentFile();
        InputStream is = null;
        OutputStream out = null;
        StringWriter writer = null;
        String content = null;
        try{
            if(excelFile.exists()){
                if(!htmlFolder.exists()){
                    htmlFolder.mkdirs();
                }
                is = new FileInputStream(excelFile);
                HSSFWorkbook workBook = new HSSFWorkbook(is);
                ExcelToHtmlConverter converter = new ExcelToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
                //设置不输出行号(1 2 3...)及列标(A B C...)等
                converter.setOutputColumnHeaders(false);
                converter.setOutputHiddenColumns(false);
                converter.setOutputColumnHeaders(false);
                converter.setOutputLeadingSpacesAsNonBreaking(false);
                converter.setOutputRowNumbers(false);
                converter.processWorkbook(workBook);

                writer = new StringWriter();
                Transformer serializer = TransformerFactory.newInstance().newTransformer();
                serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                serializer.setOutputProperty(OutputKeys.INDENT, "YES");
                serializer.setOutputProperty(OutputKeys.METHOD, "HTML");
                serializer.transform(
                        new DOMSource(converter.getDocument()),
                        new StreamResult(writer) );
                out = new FileOutputStream(htmlFile);
                content = writer.toString();
                //替换掉Sheet1 Sheet2 Sheet3...
                content = content.replaceAll("<h2>Sheet[\\d]</h2>", "")
                        .replaceAll("<h2>第[一二三四五六七八九十壹贰叁肆伍陆柒捌玖拾]页</h2>", "");

                out.write(content.getBytes("UTF-8"));
                out.flush();
                out.close();
                writer.close();
            }
        } catch (IOException | ParserConfigurationException | TransformerException e) {
            e.printStackTrace();
        } finally{
            try{
                if(is != null){
                    is.close();
                }
                if(out != null){
                    out.close();
                }
                if(writer != null){
                    writer.close();
                }
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }
}

class TestExcel {
    public static void main(String[] args) throws Exception {
        PoiExcel03lToHtml.convertExcelToHtml("D:/test.xls", "D:/test.html");
    }
}

生成html后就可以各种调用打印了。
我采用的方法是:

  1. 前台ajax访问后台转换方法
  2. 后台返回第58行的content字符串,这个字符串就是整个html页面代码。
  3. 将ajax的返回结果写入到一个新页面,然后打印这个新页面。

前台js代码:

/** * 打印方法 * @author 王晓安 * @创建时间 2017年7月19日10:32:39 * @param url 请求打印的路径 */
function print(url){ 
   
    $.ajax({
        url: url,
        data: {
            ...
        },
        type: "POST",
        dataType: "json",
        success: function(result){ 
   
            var printWin=window.open("打印窗口", "_blank");
            printWin.document.write(result);
            printWin.document.close();
            printWin.print();
            printWin.close();
        }
    });
}

测试结果:

Excel文件:
这里写图片描述


生成的html页面:
生成的html页面


js打印设置:
这里写图片描述


打印的pdf文件:
这里写图片描述

注意:

当图表比较宽,所选纸张会出现只打印部分页面情况。如下所示:
这里写图片描述

解决办法:
调整页边距:效果较小
更换打印纸张:效果明显
调整缩放:效果明显

以下图片是进行缩放的演示:
这里写图片描述


打印word与打印Excel类似:

后台word2003转HTML类:
类文件下载地址:http://download.csdn.net/detail/wangxiaoan1234/9909154

package com.srie.util.excel;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.List;

/**
 * 利用POI将Excel2003转换为HTML(支持图片但不支持Excel2007)
 */
public class PoiWord03ToHtml { 
   

    /**
     * 程序入口方法
     * @param wordPath 待读取的word路径
     * @param htmlPath 转换生成的HTML输出路径
     */
    public static void convertExcelToHtml(String wordPath, String htmlPath){
        File htmlFile = new File(htmlPath);
        File htmlFolder = htmlFile.getParentFile();
        InputStream is = null;
        OutputStream out = null;
        StringWriter writer = null;
        String content;
        try {
            is = new FileInputStream(wordPath);
            HWPFDocument wordDocument = new HWPFDocument(is);
            WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
                    DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
            //不支持λ表达式请用注释里面的代码
            wordToHtmlConverter.setPicturesManager((bytes, pt, string, f, f1) -> string); /* wordToHtmlConverter.setPicturesManager(new PicturesManager() { public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) { return suggestedName; } });*/ wordToHtmlConverter.processDocument(wordDocument); List pics = wordDocument.getPicturesTable().getAllPictures(); if (pics != null) { for (Object pic1 : pics) { Picture pic = (Picture) pic1; try { pic.writeImageContent(new FileOutputStream(htmlFolder + pic.suggestFullFileName())); } catch (FileNotFoundException e) { e.printStackTrace(); } } } Document htmlDocument = wordToHtmlConverter.getDocument(); writer = new StringWriter(); Transformer serializer = TransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "YES"); serializer.setOutputProperty(OutputKeys.METHOD, "HTML"); serializer.transform(new DOMSource(htmlDocument), new StreamResult(writer)); out = new FileOutputStream(htmlFile); content = writer.toString(); out.write(content.getBytes("UTF-8")); out.flush(); out.close(); writer.close(); } catch (IOException | ParserConfigurationException | TransformerException e) { e.printStackTrace(); } finally { try{ if(is != null){ is.close(); } if(out != null){ out.close(); } if(writer != null){ writer.close(); } }catch(IOException e){ e.printStackTrace(); } } } } class TestWord { public static void main(String[] args) throws Exception { PoiWord03ToHtml.convertExcelToHtml("D:/test.doc", "D:/test.html"); } }

测试结果:

word2003文档:
word2003文档:

HTML显示:
html显示

有哪位大神知道怎么使用poi将office2007转换成html吗?请赐教啊!!!

Exception in thread "main" org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)

同样的方法,打印.xlsx或者.docx文件时就会抛如上异常。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/210038.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • golang 永久激活破解方法

    golang 永久激活破解方法,https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月14日
    1.7K
  • c++酒店管理系统源代码_c语言酒店管理系统实验报告

    c++酒店管理系统源代码_c语言酒店管理系统实验报告现今大多数宾馆所提供的服务样式都各式各样,规模大小也是各有不同,但是归总下来,不可或缺的两类模块还是顾客和工作人员。由于对宾馆行业内部没有很深刻的理解,此次系统设计包括数据库和功能模块都是根据网上收集到的材料和个人认知上,简单模仿和具体实现的。为满宾馆管理的实际需求,本系统主要实现以下功能:入住登记:登记所入住房间号码,登记顾客入住时间,退房时间,个人信息(身份证号,手机号,姓名)退房办理:输入已经入住的房间号,确认完毕即可退房。房间查询:管理员输入正确的密码后即可对房间状态查询,和具体入住信息查

    2022年9月24日
    3
  • VBA基础知识整理[通俗易懂]

    VBA基础知识整理[通俗易懂]最近由于项目的需要,需要在Excel自定义一些函数,来完成特殊的处理,为了完成工作,就囫囵吞枣的写了一些代码,现在闲暇下来,就好好的学习一下,VBA的基础知识。1.变量1.Dim<>As<>2.规则变量名称必须使用一个字母作为第一个字符。变量名称不能使用空格,句点(.),感叹号(

    2022年6月3日
    54
  • Traceroute原理「建议收藏」

    Traceroute原理「建议收藏」通过traceroute我们可以知道信息从你的计算机到互联网另一端的主机是走的什么路径。当然每次数据包由某一同样的出发点(source)到达某一同样的目的地(destination)走的路径可能会不一样,但基本上来说大部分时候所走的路由是相同的。linux系统中,我们称之为traceroute,在MSWindows中为tracert。traceroute通过发送小的数据包到目的设备直到其返回,来测量其需要多长时间。一条路径上的每个设备traceroute要测3次。输出结果中包括每次测试的时间(ms)和

    2022年7月21日
    18
  • Map集合中value()与keySet()、entrySet()区别

    Map集合中value()与keySet()、entrySet()区别在Map集合中values():方法是获取集合中的所有的值—-没有键,没有对应关系,KeySet():将Map中所有的键存入到set集合中。因为set具备迭代器。所有可以迭代方式取出所有的键,再根据get方法。获取每一个键对应的值。keySet():迭代后只能通过get()取keyentrySet():Set<Map.Entry<K,V>>ent…

    2022年5月30日
    39
  • 2019 年 Redis面试题及答案[通俗易懂]

    2019 年 Redis面试题及答案

    2022年2月10日
    44

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号