Shortcode should always return the value instead of printing.
As per the WordPress documentation
"Any string returned (not echoed) by the shortcode handler will be inserted into the post body in place of the shortcode itself."
Please consider this code. I am placing PHP buffer before content printing and at the end I am returning the content. It should work.