Precautions for java calling system software

I have used it before, I haven’t used it for a long time, I forgot it, and it was delayed for a long time, so I recorded it for the convenience of myself and others

sample code

    private static void genPdf(String url,String pdfFilePath) throws IOException {
        String osName = System.getProperty("os.name").toUpperCase();
        log.info("osName:{}",osName);
        if(osName.contains("")){

        }
        List<String> pdfCommand = Arrays.asList(
                /*安装程序路径的bin文件夹下*/
                /*"chrome.exe --no-pdf-header-footer --headless --disable-gpu --no-sandbox --print-to-pdf="+pdfFilePath+" " +url*/
                "/usr/bin/google-chrome",
                "--no-pdf-header-footer",
                "--headless",
                "--disable-gpu",
                "--no-sandbox",
                "--print-to-pdf="+pdfFilePath,
                url

        );

        for (int i = 0; i < pdfCommand.size(); i++) {
            String command =  pdfCommand.get(i);
            log.info("command:{}",command);

        }

        ProcessBuilder pb = new ProcessBuilder(pdfCommand);
        Process pdfProcess;
        int status;
        try {
            pdfProcess = pb.start();
            try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(pdfProcess.getInputStream(), StandardCharsets.UTF_8))){
                while (pdfProcess.isAlive()) {
                    while (bufferedReader.ready()) {
                        String line = bufferedReader.readLine();
                        log.info("line:{}",line);

                    }
                }
                status = pdfProcess.waitFor();
            }catch (InterruptedException e) {
                throw new RuntimeException("PDF generation failed");
            }
            //检测是否生成成功,如果成功则创建下载pdf的路径
            if(status==0) {

                log.info("生成pdf成功");
            }
        }
        catch (IOException ex) {
            ex.printStackTrace();
            log.info("ex:{}",ex.getCause());
            throw new RuntimeException("PDF转化失败");
        }
    }

Precautions:

Note 1: The software must write the absolute path, even if the environment variable is configured; the environment variable is configured to ensure that the absolute address does not need to be entered in the black window, but the java call cannot, and the absolute path must be entered

Note 2: Multiple parameters, one command line per parameter, and no spaces at the beginning and end

Guess you like

Origin blog.csdn.net/wangwenzhe222/article/details/130248478