[nodejs] html to image 로 이미지에 글자 및 이미지 넣기 / 한글 깨짐 오류 해결
2024. 6. 26. 16:46ㆍ개발/nodejs
body.html
<html>
<head>
<meta charset="utf-8">
<style>
.main {
position: relative;
}
.main-img {
width: 100%;
}
.sub-img {
position: absolute;
width: {imgWidth};
top: {imgTop};
left: {imgLeft};
transform: translate(-50%, -50%);
{useImage}
}
.sub-txt {
position: absolute;
top: {txtTop};
left: {txtLeft};
transform: translate(-50%, -50%);
color: {txtColor};
font-size: {fontSize};
}
</style>
<body>
<div class="main">
<img class="main-img" src="{mainImgPath}">
<img class="sub-img" src="{subImgPath}">
<div class="sub-txt">
<span>{txtInfo}</span>
</div>
</div>
</body>
</html>
app.js
const fs = require("fs");
const nodeHtmlToImage = require("node-html-to-image");
...
const contentMig = (html, data)=>{
Object.keys(data).forEach(key=>{
const rex = new RegExp(`\{${key}\}`, "g");
html = html.replace(rex, data[key]);
});
// 서브 이미지 사용여부 확인 ( Default: true )
if (data.useImage === false) html.replace("{useImage}", "display: none;")
else html.replace("{useImage}", "");
// 텍스트 색상 설정 없을경우 black
if (!data.txtColor) html = html.replace("{txtColor}", "black");
return html;
}
...
module.exports = function (req, res, next) {
const html = fs.readFileSync("./body.html").toString();
// const data = req.body;
let data = {};
// 메인 이미지 주소
data.mainImgPath = "https://aaa.bbb.cc/ddd.png";
// 이미지에 넣을 서브 이미지 주소
data.subImgPath = "https://aaa.bbb.cc/eee.png";
// 서브 이미지 크기
data.imgWidth = "300px";
// 서브 이미지 위치
data.imgTop = "500px";
data.imgLeft = "100px";
// 이미지에 넣을 텍스트 내용
data.txtInfo = "내용내용내용";
// 이미지에 넣을 텍스트 크기
data.fontSize = "50px";
// 이미지에 넣틀 텍스트 위치
data.txtTop = "900px";
data.txtLeft = "100px";
const image = await nodeHtmlToImage({
html: contentMig(html, data),
// 이미지 퀄리티
quality: 100
});
res.writeHead(200, { 'Content-Type': 'image/png' });
res.end(image, 'binary');
}
...
위 처럼 하였을때 로컬에서는 문제 없이 작동 되었으나, ubuntu 환경에서는 아래와 같은 오류가 발생하였다.
ERROR [ExceptionsHandler] Unable to launch browser, error message: Could not find Chrome ...
...
크로미움 브라우저 설치 후 경로를 지정해줘야 한다.
sudo apt-get install chromium-browser
설치 후 app.js 내용도 일부 수정
...
const image = await nodeHtmlToImage({
html: html,
// 이미지 퀄리티
quality: 100,
puppeteerArgs: {
executablePath: '/usr/bin/chromium-browser',
args: ['--no-sandbox', '--disable-setuid-sandbox'],
}
});
...
이후 정상 실행은 되었으나 폰트 문제로 한글이 깨져 사각형 모양으로 나오는 오류가 발생하였다.
( local 에서는 기본적으로 한글 폰트를 지원해주어 잘 나온다. )
한글 폰트 설치
cd /usr/share/fonts
sudo wget http://cdn.naver.com/naver/NanumFont/fontfiles/NanumFont_TTF_ALL.zip
# unzip 이 설치되어 있지 않을경우 설치
apt-get install zip unzip
sudo unzip ./NanumFont_TTF_ALL.zip
sudo rm ./NanumFont_TTF_ALL.zip
설치후 다시 테스트 하였을 때 한글이 정상적으로 나오는 것을 확인할 수 있었다.
'개발 > nodejs' 카테고리의 다른 글
[Mac m1] canvas node package 설치 오류 (1) | 2024.06.04 |
---|---|
[Mac] nvm / node.js 설치 (1) | 2024.06.04 |
nodejs/docker/socket.io(+redis) 여러개의 서버로 채팅 (0) | 2021.11.03 |
nodejs/docker 환경에서 파일 업로드 이슈 해결 (0) | 2021.11.02 |
nodejs / tensorflow.js 참고 (0) | 2021.10.25 |